zoukankan      html  css  js  c++  java
  • 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();
    	}
    
    }


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    用SQL查询方式显示GROUP BY中的TOP解决方法[转]
    三大UML建模工具Visio、Rational Rose、PowerDesign的区别
    Eclipse HTML Editor
    [转]跨平台开发:PhoneGap移动开发框架初探
    取消开机显示登陆页面
    PhoneGap开发环境搭建
    显示器不能全屏及开机慢解决方案
    调用webservice超时问题的解决[转]
    最简单的JAVA解析XML字符串方法
    适用于vue项目的打印插件(转载)
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4750181.html
Copyright © 2011-2022 走看看