2) Write a Java program that implements producer consumer problem (consider a single
resource slot and single producer and consumer threads).
import java.util.Scanner;
//A correct implementation of a producer and consumer.
class Q {
int n;
int a;
boolean valueSet = false;
private Scanner s;
synchronized int get() {
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consumed: " + a);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("enter the value u want to push in ");
s = new Scanner(System.in);
a = s.nextInt();
System.out.println("Produced#: " + a);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 1;
q.put(i);
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
q.get();
}
}
class producerconsumer {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-Z to stop.");
}
0 comments:
Post a Comment