如下阻塞队列+线程的代码,很常见,当服务停止时,如何停止被BlockingQueue阻塞的线程?
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的元素代表停止事件,线程取到这个特殊元素时就跳出循环:
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) {
} } } });

技术
今日推荐
PPT
阅读数 126
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信