-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueueDemo.java
More file actions
43 lines (43 loc) · 992 Bytes
/
BlockingQueueDemo.java
File metadata and controls
43 lines (43 loc) · 992 Bytes
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
import java.util.concurrent.*;
class Producer implements Runnable
{
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue){
this.queue = queue;
}
public void run(){
for(int i=0; i<=10; i++){
try{
Thread.sleep((int)(Math.random()*10));
queue.put(i);
System.out.println("Produce "+i+".");
}catch(InterruptedException ex){}
}
}
}
class Consumer implements Runnable
{
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue){
this.queue = queue;
}
public void run(){
for(int i=0; i<=10; i++){
try{
Thread.sleep((int)(Math.random()*20));
Integer product = queue.take();
System.out.println("Consume "+product+".");
}catch(InterruptedException ex){}
}
}
}
class BlockingQueueDemo
{
public static void main(String[] args)
{
BlockingQueue<Integer> queue =
new ArrayBlockingQueue<>(3);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}