-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_communication.java
More file actions
53 lines (47 loc) · 1.51 KB
/
thread_communication.java
File metadata and controls
53 lines (47 loc) · 1.51 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
class SharedResource {
private int number;
private boolean isAvailable = false;
public synchronized int getNumber() throws InterruptedException {
while (!isAvailable) {
wait(); // Wait until number is available
}
isAvailable = false;
notify(); // Notify the producer
return number;
}
public synchronized void setNumber(int number) throws InterruptedException {
while (isAvailable) {
wait(); // Wait until number is consumed
}
this.number = number;
isAvailable = true;
notify(); // Notify the consumer
}
}
public class ProducerConsumerExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
resource.setNumber(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
int value = resource.getNumber();
System.out.println("Consumed: " + value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}