-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
87 lines (76 loc) · 1.67 KB
/
ProducerConsumer.java
File metadata and controls
87 lines (76 loc) · 1.67 KB
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
class Q{
int n;
boolean available=false;
synchronized int get(){
while(available == false){
try{
wait();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println("Consumer :"+n);
available = false;
notify();
return n;
}
synchronized void put(int n){
this.n = n;
while(available == true){
try{
wait();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println("Producer :"+n);
available = true;
notify();
}
}
class Producer implements Runnable{
Q q;
public Producer(Q q) {
this.q = q;
Thread t = new Thread(this);
t.start();
}
public void run(){
int i = 0;
while(true){
q.put(i++);
System.out.println(q.n);
try {
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
Q q;
public Consumer(Q q) {
this.q = q;
Thread t = new Thread(this);
t.start();
}
public void run(){
while(true){
q.get();
try {
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
class ProducerConsumer {
public static void main(String a[]){
Q q = new Q();
q.n=0;
Producer p = new Producer(q);
Consumer c = new Consumer(q);
}
}