验证阻塞队列超时机制

作者最近学习了一下线程池源码,线程池判断线程是否超时需要回收是根据任务队列超时来判断的,本人初学阻塞队列,不明白是怎么判断超时的,写了个程序验证一下,望指正。

下面附上代码:

/**
 * 验证BlockingQueue中poll方法超时机制
 * 从BlockingQueue中poll元素时,如果队列为空,则等待传入的时间,如果队列任然为空,则表示poll超时
 * @date 2016-8-29
 */
public class Test2 {

private LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();

private Integer startValue = 0;

private Integer work = null;

//添加任务
class AddThread extends Thread{
public void run() {
//10秒添加一次
while(true){
queue.add(startValue);
startValue++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

//取出任务
class PollThread extends Thread{
public void run() {
Long startTime = 0l;
Long endTime = 0l;
while(true){
startTime = System.currentTimeMillis();
try {
//5秒超时
work = queue.poll(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
endTime = System.currentTimeMillis();
if(work == null){
System.out.println("取出任务超时:" + (endTime - startTime) + "毫秒");
}else{
System.out.println("取出任务用时:" + (endTime - startTime) + "毫秒,任务:" + work);
}
}
}
}

public static void main(String[] args) {
Test2 t2 = new Test2();
AddThread add = t2.new AddThread();
PollThread poll = t2.new PollThread();
add.start();
poll.start();
}
}


运行结果如下:

取出任务用时:1毫秒,任务:0
取出任务超时:5000毫秒
取出任务用时:4999毫秒,任务:1
取出任务超时:5002毫秒
取出任务用时:4999毫秒,任务:2
取出任务超时:5001毫秒

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值