前言:
现在兄弟们对“python queue阻塞”大体比较关切,我们都想要知道一些“python queue阻塞”的相关资讯。那么小编在网络上网罗了一些关于“python queue阻塞””的相关知识,希望兄弟们能喜欢,姐妹们快快来了解一下吧!如下阻塞队列+线程的代码,很常见,当服务停止时,如何停止被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) { } } }});
标签: #python queue阻塞