1. Thread safe
2. Allow duplicates
3. Not allowed null values
Types
- ArrayBlockingQueue
- DelayQueue
- LinkedBlockingQueue
- PriorityBlockingQueue
- SynchronousQueue
Example
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BlockingQueueExamples {
public static void main(String[] args) throws InterruptedException, ExecutionException {
BlockingQueue<String> bq = new ArrayBlockingQueue<String>(1000);
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.submit(new ConsumerThread(bq));
exec.submit(new ProducerThread(bq));
}
}
class ProducerThread implements Callable<Object> {
private BlockingQueue<String> blockingQueue;
public ProducerThread(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
}
public Object call() throws Exception {
System.out.println("Producer Started:");
Thread.sleep(1000);
blockingQueue.put("vinod");
Thread.sleep(1000);
blockingQueue.put("vinod1");
Thread.sleep(1000);
blockingQueue.put("vinod2");
return null;
}
}
class ConsumerThread implements Callable<Object> {
private BlockingQueue<String> blockingQueue;
public ConsumerThread(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
}
public Object call() throws Exception {
System.out.println("Consumer Started:");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
return null;
}
}