![](/img/trans.png)
[英]What happens to the Executor FixedThreadPool after execution, as executor does not have a shutdown method?
[英]Why does executor not shutdown?
我正在使用帶有阻塞隊列的執行程序來處理Producer消費者模式。我無法理解為什么此池沒有關閉並且主線程終止?
想法是我只有一個生產者和多個消費者(100)
我有一個毒葯項目(-1),食用時會觸發游泳池關閉。
一切似乎都工作正常,但該程序永不終止。
這是我的代碼:
生產者類別:
class Producer implements Runnable {
protected BlockingQueue queue = null;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
for (int i = 0; i < 30000; i++) {
queue.put(i);
// System.out.println("Producer ID "+Thread.currentThread().getId()+" is adding task : "+i);
}
// poison pill
// System.out.println("Poison number added! "+Thread.currentThread().getId());
queue.put(-1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消費類:
class Consumer implements Runnable {
protected BlockingQueue queue = null;
ConcurrentHashMap<Integer, Integer> hashmap;
public Consumer(BlockingQueue queue,
ConcurrentHashMap<Integer, Integer> hashmap) {
this.queue = queue;
this.hashmap = hashmap;
}
public void run() {
try {
//while (ExecutorTest.isRunning) {
Integer i = (Integer) queue.take();
System.out.println("Consumer " + Thread.currentThread().getId()
+ ": taking Task : " + i);
if (i == -1) {
//queue.put(i);
ExecutorTest.isRunning = false;
// System.out.println("Setting isRunning to false : "+Thread.currentThread().getId());
//return;
}
hashmap.put(i, i);
//}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主程序:
公共類ExecutorTest {
static BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
static ConcurrentHashMap<Integer, Integer> hashmap = new ConcurrentHashMap<Integer, Integer>();
static volatile boolean isRunning = true;
public static void main(String[] args) {
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue, hashmap);
new Thread(producer).start();
ExecutorService executorService = Executors.newFixedThreadPool(100);
// wait for the threads to finish
while (isRunning) {
executorService.execute(consumer);
};
try {
executorService.shutdown();
System.out.println("SHUT DOWN THREAD POOL");
while(!executorService.isShutdown()){
}
executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("HASHMAP SIZE : " + hashmap.size());
try {
queue.put(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void printHashMap() {
for (Map.Entry<Integer, Integer> map : hashmap.entrySet()) {
System.out.println("Entry " + map.getKey() + ":" + map.getValue());
}
}
}
您在這里產生了很多潛在的消費者:
while (isRunning) {
executorService.execute(consumer);
};
這些消費者將queue.take
並且永遠無法完成。 只有第一個能夠接受-1的人將被關閉。
嘗試shutdownNow()
,但是老實說,我不明白您while循環的目的,您不應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.