Lecture Videos
  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      // Create a thread pool with two threads
  9      ExecutorService executor = Executors.newFixedThreadPool(2);
 10      executor.execute(new ProducerTask());
 11      executor.execute(new ConsumerTask());
 12      executor.shutdown();
 13    }
 14  
 15    // A task for adding an int to the buffer
 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++); // Add any value to the buffer, say, 1
 23            // Put the thread into sleep
 24            Thread.sleep((int)(Math.random() * 10000));
 25          }
 26        } 
 27        catch (InterruptedException ex) {
 28          ex.printStackTrace();
 29        }
 30      }
 31    }
 32  
 33    // A task for reading and deleting an int from the buffer
 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            // Put the thread into sleep
 40            Thread.sleep((int)(Math.random() * 10000));
 41          }
 42        } 
 43        catch (InterruptedException ex) {
 44          ex.printStackTrace();
 45        }
 46      }
 47    }
 48  }