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(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。