1 import java.util.concurrent.*;
2
3 public class ConsumerProducerUsingBlockingQueue {
4 private static ArrayBlockingQueue<Integer> buffer =
5 new ArrayBlockingQueue<>(2);
6
7 public static void main(String[] args) {
8
9 ExecutorService executor = Executors.newFixedThreadPool(2);
10 executor.execute(new ProducerTask());
11 executor.execute(new ConsumerTask());
12 executor.shutdown();
13 }
14
15
16 private static class ProducerTask implements Runnable {
17 public void run() {
18 try {
19 int i = 1;
20 while (true) {
21 System.out.println("Producer writes " + i);
22 buffer.put(i++);
23
24 Thread.sleep((int)(Math.random() * 10000));
25 }
26 }
27 catch (InterruptedException ex) {
28 ex.printStackTrace();
29 }
30 }
31 }
32
33
34 private static class ConsumerTask implements Runnable {
35 public void run() {
36 try {
37 while (true) {
38 System.out.println("\t\t\tConsumer reads " + buffer.take());
39
40 Thread.sleep((int)(Math.random() * 10000));
41 }
42 }
43 catch (InterruptedException ex) {
44 ex.printStackTrace();
45 }
46 }
47 }
48 }