BlockingQueue测试使用

package queue;

import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class TestBlockingQueue {  
	  
    public static void main(String[] args) {  
        final BlockingQueue<Integer> queue=new LinkedBlockingQueue<Integer>(3);  
        final Random random=new Random();  
          
        class Producer implements Runnable{  
            @Override  
            public void run() {  
                while(true){  
                    try {  
                        int i=random.nextInt(100);  
                        long start=new Date().getTime();
                        queue.put(i);//,put方法往底部添加数据,若 当队列达到容量时候,会自动阻塞的
                        long end=new Date().getTime();
                        System.out.println("等待"+String.valueOf(end-start)+"毫秒");
                        Iterator it=queue.iterator();
                        while(it.hasNext()){
                        	System.out.println(it.next());
                        }
                        if(queue.size()==3)  
                        {  
                            System.out.println("full");  
                           
                        }  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
          
        class Consumer implements Runnable{  
            @Override  
            public void run() {  
                while(true){  
                    try {  
                        queue.take();//从队列头部取出数据,当队列为空时,也会自动阻塞  
                        Thread.sleep(3000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
          
        new Thread(new Producer()).start();  
        new Thread(new Consumer()).start();  
    }  
  
}  

打印结果

等待1毫秒
等待0毫秒
71
等待0毫秒
71
19
等待0毫秒
71
19
80
full
等待3000毫秒
19
80
29
full
等待3000毫秒
80
29
47
full
等待3001毫秒
29
47
83
full
等待3000毫秒
47
83
17
full
等待3000毫秒
83
17
89
full
等待3000毫秒
17
89
63
full
等待3001毫秒
89
63
63
full
等待3000毫秒
63
63
67
full
等待3000毫秒
63
67
15
full
等待3001毫秒
67
15
86
full
 

转载于:https://my.oschina.net/liangzhenghui/blog/834161

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值