阻塞队列和多线程使用者,如何知道何时停止

阻塞队列和多线程使用者,如何知道何时停止,第1张

阻塞队列和多线程使用者,如何知道何时停止

您应该

take()
从队列继续。您可以使用毒药告诉工人停下来。例如:

private final Object POISON_PILL = new Object();@Overridepublic void run() {    //worker loop keeps taking en element from the queue as long as the producer is still running or as     //long as the queue is not empty:    while(isRunning) {        System.out.println("Consumer "+Thread.currentThread().getName()+" START");        try { Object queueElement = inputQueue.take(); if(queueElement == POISON_PILL) {      inputQueue.add(POISON_PILL);//notify other threads to stop      return; } //process queueElement        } catch (Exception e) { e.printStackTrace();        }    }}//this is used to signal from the main thread that he producer has finished adding stuff to the queuepublic void finish() {    //you can also clear here if you wanted    isRunning = false;    inputQueue.add(POISON_PILL);}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5003030.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存