forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
39 lines (39 loc) · 1.06 KB
/
ProducerConsumer.java
File metadata and controls
39 lines (39 loc) · 1.06 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
// filename: ProducerConsumer.java
// Compile: javac ProducerConsumer.java
// Run: java ProducerConsumer
import java.util.concurrent.*;
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> q) { this.queue = q; }
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Produced: " + i);
queue.put(i);
Thread.sleep(500);
}
queue.put(-1); // poison pill
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> q) { this.queue = q; }
public void run() {
try {
while (true) {
int val = queue.take();
if (val == -1) break;
System.out.println("Consumed: " + val);
Thread.sleep(700);
}
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
public class ProducerConsumer {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}