作者最近学习了一下线程池源码,线程池判断线程是否超时需要回收是根据任务队列超时来判断的,本人初学阻塞队列,不明白是怎么判断超时的,写了个程序验证一下,望指正。
下面附上代码:
/**
* 验证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毫秒