Monday, September 8, 2014

JAVA BlockingQueue SIMPLE CODE

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            System.out.println("Taken:"+queue.take());
            System.out.println("Taken:"+queue.take());
            System.out.println("Taken:"+queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            queue.put("1");
            System.out.println("Put:1");
            Thread.sleep(1000);
         
            System.out.println("Put:220");
            queue.put("220");
            Thread.sleep(1000);
         
            System.out.println("Put:38");
            queue.put("38");
            Thread.sleep(1000);          
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class BlockingQueueFlight {

    public static void main(String[] args) throws Exception {

        BlockingQueue queue = new ArrayBlockingQueue(1024);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}

No comments:

Post a Comment