Wednesday 18 December 2019

BlockingQueue Implementaion in java

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueExample {

public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
     Producer producer = new Producer(queue);
     Consumer consumer = new Consumer(queue);
     new Thread(producer).start();
     new Thread(consumer).start();
     Thread.sleep(4000);
}
}

class Producer implements Runnable{

BlockingQueue< String> q=null;
public Producer(BlockingQueue<String> queue) {
this.q=queue;
}
public void run() {
try{
q.put("1");
Thread.sleep(1000);
q.put("2");
Thread.sleep(1000);
q.put("3");
Thread.sleep(1000);
q.put("4");
}
catch (Exception e) {
e.printStackTrace();
}
}

}

class Consumer implements Runnable {

BlockingQueue<String> queue=null;

public Consumer(BlockingQueue< String> b) {
this.queue=b;
}
public void run() {
try {
for (String string : queue) {
System.out.println(queue.take());
}
         

}
catch (Exception e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment