-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
70 lines (52 loc) · 1.57 KB
/
ProducerConsumer.java
File metadata and controls
70 lines (52 loc) · 1.57 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
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumer {
public static void main(String[] args) {
BlockingQueue<String> queue=new ArrayBlockingQueue<>(5);
Thread p1=new Thread(new Producer(queue));
Thread p2=new Thread(new Producer(queue));
Thread c1=new Thread(new Consumer(queue));
Thread c2=new Thread(new Consumer(queue));
p1.start();
p2.start();
c1.start();
c2.start();
}
}
class Producer implements Runnable{
private BlockingQueue<String> queue;
Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run(){
while (true){
try{
queue.put("Product");
System.out.println("Produced by " + Thread.currentThread().getName());
Thread.sleep(1000);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
}
class Consumer implements Runnable{
private BlockingQueue<String> queue;
Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run(){
while(true){
try{
String product = queue.take();
System.out.println("Consumed by " + Thread.currentThread().getName());
Thread.sleep(1200);
}catch(InterruptedException e){
throw new RuntimeException(e);
}
}
}
}