如何停止被BlockingQueue阻塞的线程

如下阻塞队列+线程的代码,很常见,当服务停止时,如何停止被BlockingQueue阻塞的线程?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(10);
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Integer el = blockingQueue.take();
System.out.println(el);
} catch (InterruptedException e) {

}
}
}
});

方法是当服务停止时,触发一个操作,给blockingQueue放一个特殊的元素,如上面,传一个值为-1的元素代表停止事件,线程取到这个特殊元素时就跳出循环:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final int STOP_CODE = -1;
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(10);
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Integer el = blockingQueue.take();
// quit loop when receive stop event
if (STOP_CODE == el) {
break;
}
//do something useful
System.out.println(el);
} catch (InterruptedException e) {

}
}
}
});
零壹视界 wechat
扫描关注我的微信公众号
喜欢就赞赏一下
0%