首页 > 代码库 > LinkedBlockingQueue多线程测试
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(); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。