2011.08.30(2)——— java BlockingQueue ExecutorService

2011.08.30(2)——— java BlockingQueue ExecutorService
参考: http://www.iteye.com/topic/366591
http://topic.csdn.net/u/20091226/16/b1337a92-a4a2-463e-a04e-7226e5fa78d2.html

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


package com.lp;
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();
	}
	
}




你可能感兴趣的:(java,BlockingQueue,executorService)