[英]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.