日期:2014-05-16  浏览次数:20452 次

java.util.concurrent 之四:LinkedBlockingQueue
    并发库中的BlockingQueue是一个比较好玩的类,顾名思义,就是阻塞队列。该类主要提供了两个方法put()和take(),前者将一个对象放到队列尾部,如果队列已经满了,就等待直到有空闲节点;后者从head取一个对象,如果没有对象,就等待直到有可取的对象。
package test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class MyBlockingQueue extends Thread{
	public static BlockingQueue<String> queue=new LinkedBlockingQueue<String>(3);
	private int index;
	public MyBlockingQueue(int i){
		this.index=i;
	}

	public void run(){
		try{
			queue.put(String.valueOf(this.index));
			System.out.println("put {"+this.index+"} into queue!");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		ExecutorService service=Executors.newCachedThreadPool();
		for( int i=0; i<10; i++){
			service.submit(new MyBlockingQueue(i));
		}
		Thread thread = new Thread(){
			public void run(){
				try{
					while(true){
						Thread.sleep((int)(Math.random()*1000));
						if(MyBlockingQueue.queue.isEmpty()) break;
						String str=MyBlockingQueue.queue.take();
						System.out.println("take {" + str+"} out of queue!");
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		};
		service.submit(thread);
		service.shutdown();
	}
	
}		

可能的运行结果:
put {0} into queue!
put {1} into queue!
put {3} into queue!
take {0} out of queue!
put {2} into queue!
take {1} out of queue!
put {7} into queue!
take {3} out of queue!
put {5} into queue!
take {2} out of queue!
put {4} into queue!
take {7} out of queue!
put {6} into queue!
put {9} into queue!
take {5} out of queue!
take {4} out of queue!
put {8} into queue!
take {6} out of queue!
take {9} out of queue!
take {8} out of queue!