gpt4 book ai didi

java - 为什么执行器不关闭?

转载 作者:行者123 更新时间:2023-12-02 03:56:16 25 4
gpt4 key购买 nike

我正在使用带有阻塞队列的执行器来研究生产者消费者模式。我无法理解为什么这个池没有关闭并且主线程终止?

想法是我只有一个生产者和多个消费者(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();
}
}
}

主要程序:

公共(public)类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 循环的目的,你不应该这样做。

关于java - 为什么执行器不关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com