如何停止被BlockingQueue阻塞的线程

2019-09-29  本文已影响0人  零壹视界

如下阻塞队列+线程的代码,很常见,当服务停止时,如何停止被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) {

            }
        }
    }
});
上一篇下一篇

猜你喜欢

热点阅读