-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathProducerConsumerWaitNotify.java
80 lines (70 loc) · 1.61 KB
/
ProducerConsumerWaitNotify.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
package misc;
import java.util.ArrayList;
import java.util.List;
public class ProducerConsumerWaitNotify {
static List<Integer> list = new ArrayList<Integer>();
static class Producer implements Runnable {
List<Integer> list;
public Producer(List<Integer> list) {
this.list = list;
}
@Override
public void run() {
synchronized (list) {
for (int i = 0; i <= 5; i++) {
if (list.size() >= 1) {
try {
System.out.println("Producer is waiting ...");
list.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("Produce: " + i);
list.add(i);
list.notifyAll();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
static class Consumer implements Runnable {
List<Integer> list;
public Consumer(List<Integer> list) {
this.list = list;
}
@Override
public void run() {
synchronized (list) {
for (int i = 0; i <= 5; i++) {
while (list.isEmpty()) {
System.out.println("Consumer is waiting...");
try {
list.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
int k = list.remove(0);
System.out.println("Consume: " + k);
list.notifyAll();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread producer = new Thread(new Producer(list));
Thread consumer = new Thread(new Consumer(list));
producer.start();
consumer.start();
}
}