LinkedBlockingQueue
ArrayBlockingQueue
SynchronizedBlockingQueue
TestBlockingQueue.java
package com.test.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestBlockingQueue {
static void getKey(){
try {
(new BufferedReader(new InputStreamReader(System.in))).readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
static void getKey(String msg){
System.out.println(msg);
getKey();
}
static void test(String msg, BlockingQueue<LiftOff> queue){
System.out.print(msg);
LiftOffRunner runner=new LiftOffRunner(queue);
Thread t=new Thread(runner);
t.start();
for(int i=0;i<5;i++){
runner.add(new LiftOff(5));
}
getKey("Press 'Enter'("+msg+")");
t.interrupt();
System.out.println("finished "+msg+" test");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
test("LinkedBlockingQueue",new LinkedBlockingQueue<LiftOff>());
test("ArrayBlockingQueue",new ArrayBlockingQueue<LiftOff>(3));
test("SynchronousQueue",new SynchronousQueue<LiftOff>());
}
}
class LiftOffRunner implements Runnable{
private BlockingQueue<LiftOff> rockets;
public LiftOffRunner(BlockingQueue<LiftOff> queue){
this.rockets=queue;
}
public void add(LiftOff lo){
try{
rockets.put(lo);
}catch(InterruptedException e){
System.out.println("interrupted during put()");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(!Thread.interrupted()){
LiftOff rocket;
try {
rocket = rockets.take();
rocket.run();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("LiftOff Runner Exiting!!");
}
}
class LiftOff implements Runnable {
static int taskCount=0;
private final int id=taskCount++;
protected int countDown=10;
public LiftOff(){}
public LiftOff(int countDown){
this.countDown=countDown;
}
public String status(){
return "#"+id+"("+(countDown==0?"LiftOff":countDown)+"), ";
}
@Override
public void run() {
// TODO Auto-generated method stub
while(countDown-->0){
System.out.print(status());
Thread.yield();
}
}
}