Skip to content

Commit 96ae339

Browse files
committed
Create producer_consumer.java
1 parent cc7bdf4 commit 96ae339

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Write a java program that corrects implements of producer consumer problem.
3+
*/
4+
5+
6+
package Producer_Consumer;
7+
8+
class Q {
9+
int n;
10+
boolean valueSet = false;
11+
12+
synchronized int get() {
13+
if (!valueSet)
14+
try {
15+
wait();
16+
} catch (InterruptedException e) {
17+
System.out.println("Interrupted Exception caught");
18+
}
19+
System.out.println("Got:" + n);
20+
valueSet = false;
21+
notify();
22+
return n;
23+
}
24+
25+
synchronized void put(int n) {
26+
if (valueSet)
27+
try {
28+
wait();
29+
} catch (InterruptedException e) {
30+
System.out.println("Interrupted Exception caught");
31+
}
32+
this.n = n;
33+
valueSet = true;
34+
System.out.println("Put:" + n);
35+
notify();
36+
}
37+
}
38+
39+
40+
class Producer implements Runnable {
41+
Q q;
42+
43+
Producer(Q q) {
44+
this.q = q;
45+
new Thread(this, "Producer").start();
46+
}
47+
48+
public void run() {
49+
int i = 0;
50+
while (true) {
51+
q.put(i++);
52+
}
53+
}
54+
}
55+
56+
57+
class Consumer implements Runnable {
58+
Q q;
59+
60+
Consumer(Q q) {
61+
this.q = q;
62+
new Thread(this, "Consumer").start();
63+
}
64+
65+
public void run() {
66+
while (true) {
67+
q.get();
68+
}
69+
}
70+
}
71+
72+
public class producer_consumer {
73+
public static void main(String[] args){
74+
Q q = new Q();
75+
new Producer(q);
76+
new Consumer(q);
77+
}
78+
}

0 commit comments

Comments
 (0)