-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterThreadExample.java
More file actions
56 lines (47 loc) · 1.52 KB
/
InterThreadExample.java
File metadata and controls
56 lines (47 loc) · 1.52 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
package Thread.Day_6;
class DataBox {
private int data;
private boolean available = false;
public synchronized void produce(int value) throws InterruptedException {
while (available) { // wait, if data not yet consumed
wait();
}
this.data = value;
System.out.println("Produced data: " + data);
available = true;
notify(); // notify consumer like data has been produced, please consume.
}
public synchronized void consume() throws InterruptedException {
while (!available) { // wait, if data not yet produce
wait();
}
System.out.println("Consumed data: " + data);
available = false;
notify(); // notify producer like data has been consumed, please produce new data
}
}
public class InterThreadExample {
public static void main(String[] args) {
DataBox dataBox = new DataBox();
Thread producer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
dataBox.produce(i);
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
});
Thread consumer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
dataBox.consume();
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
});
producer.start();
consumer.start();
}
}