forked from ronijpandey/Java-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProduConsum.java
119 lines (86 loc) · 2.15 KB
/
ProduConsum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package javacodes;
import java.util.*;
public class ProduConsum{
public static void main(String []args)throws InterruptedException
{
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
Thread pt=new Thread(p);
Thread ct=new Thread(c);
pt.start();
ct.start();
pt.join();
ct.join();
System.out.println("Existing main Thread");
}
}
class Producer implements Runnable
{
Queue queue;
Producer(Queue queue)
{
this.queue=queue;
}
public void run()
{
int i=0;
while(i<=20)
{
queue.set(i);
i++;
}
System.out.println("Existing Producer Thread");
queue.producerAlive=false;
}
}
class Consumer implements Runnable
{
Queue queue;
Consumer(Queue queue)
{
this.queue=queue;
}
public void run()
{
while(queue.producerAlive)
{
queue.get();
}
System.out.println("Existing Consumer Thread");
}
}
class Queue
{
int n=0;
boolean valueset=false;
boolean producerAlive=true;
synchronized void get()
{
if(!valueset)
{
try {
wait();
} catch (InterruptedException e) {
System.out.println("Error");
}
}
valueset=false;
System.out.println("Got"+" "+this.n);
notify();
}
synchronized void set(int n)
{
if(valueset)
{
try {
wait();
} catch (InterruptedException e) {
System.out.println("Value set");
}
}
this.n=n;
valueset=true;
notify();
}
}