Thursday, April 5, 2018

BlockingQueue Example Producer Consumer Basic

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
    static Queue queue = new LinkedList();
    static int capacity=3;

    public static void main(String[] args) {
        final Worker work = new Worker();
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                try {
                    work.produce();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable(){
            public void run(){
                try {
                    work.consume();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    } 
    static class Worker {
        int number=0;
        public void produce() throws Exception {

            while(true){
                synchronized(this){
                    while(queue.size()==capacity){
                        System.out.println("Waiting to get Removed...");
                        wait();
                    }
                    number++;
                    queue.add(number);
                    System.out.println("Added: "+number);
                    notifyAll();
                    Thread.sleep(500);
                }
            }

        }
        public void consume() throws Exception {
            while(true){
                synchronized(this){
                    while(queue.isEmpty()){
                        System.out.println("Waiting to get Added...");
                        wait();
                    }
                    Object t = queue.remove();
                    System.out.println("Removed: "+t);
                    notifyAll();
                    Thread.sleep(500);
                }
            }
        }    
    }
}


//Output
Added: 1
Added: 2
Added: 3
Removed: 1
Added: 4
Waiting to get Removed...
Removed: 2
Removed: 3
Removed: 4
Waiting to get Added...
Added: 5
Added: 6
Removed: 5
Removed: 6
Waiting to get Added...
Added: 7

No comments:

Post a Comment