LinkedBlockingQueue多线程测试

public class FillQueueThread extends Thread {
	private Queue queue;
	public FillQueueThread(Queue queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		while(true){
			try {
				boolean added = queue.offer(UUID.randomUUID().toString());
				if(added) {
					System.out.println(Thread.currentThread().getName()+" add 1 element");
				}else{
					System.out.println(Thread.currentThread().getName()+" is blocked, wait");
					//this.wait(); //no need to invoked wait
				}
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}	


public class PollQueueThread extends Thread {
	private Queue queue;
	public PollQueueThread(Queue queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		while(true){
			try {
				Object el = queue.poll();
				if(null == el){
					System.out.println(Thread.currentThread().getName()+" is blocked, wait");
					//this.wait(); //no need to invoked wait
				}else{
					System.out.println(Thread.currentThread().getName()+" pool 1 element");
				}
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

public class MonitorQueueThread extends Thread {
	private Queue queue;
	public MonitorQueueThread(Queue queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		while(true){
			System.err.println("queue size:"+queue.size());
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

public class HelloQueue {

	public static void main(String[] args) {
		//ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(500,true);
		LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(500);
		int threadFillNumber = 10;
		int threadPollNumber = 3;
		for(int i=0; i<threadFillNumber; i++){
			FillQueueThread th = new FillQueueThread(queue);
			th.start();
		}
		for(int i=0; i<threadPollNumber; i++){
			PollQueueThread th = new PollQueueThread(queue);
			th.start();
		}
		
		MonitorQueueThread monitor = new MonitorQueueThread(queue);
		monitor.start();
	}

}


LinkedBlockingQueue多线程测试,布布扣,bubuko.com

LinkedBlockingQueue多线程测试

上一篇:mysql float double 类型


下一篇:access函数之判断文件属性