gpt4 book ai didi

java - 启动先前关闭的 ExecutorService 时出现 RejectedExecutionException

转载 作者:行者123 更新时间:2023-12-01 12:57:08 25 4
gpt4 key购买 nike

我正在尝试实现生产者-消费者模式,并且我希望能够阻止消费者。到目前为止我写道:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class Test {

public static void main(final String[] args) throws InterruptedException {
final BlockingQueue<String> messages = new LinkedBlockingQueue<>(100);
final ExecutorService producer = Executors.newSingleThreadExecutor();
final Consumer consumer = new Consumer(messages);

producer.execute(new Runnable() {

@Override
public void run() {
for (int i = 0;; i++) {
try {
messages.put("Message " + i);
Thread.sleep(500);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

});

consumer.start();

consumer.stop();
consumer.start();
}

private static class Consumer {

private final ExecutorService consumer = Executors.newSingleThreadExecutor();
private final BlockingQueue<String> messages;

public Consumer(final BlockingQueue<String> m) {
messages = m;
}

public void start() {
consumer.execute(new Runnable() {

@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println(messages.take());
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}

});
}

public void stop() {
consumer.shutdownNow();
}

}

}

但这总是给我上面的异常(exception)。控制台输出为:

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task Test$Consumer$1@31602bbc rejected from java.util.concurrent.ThreadPoolExecutor@20d75cf7[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2048)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:821)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1372)
at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:628)
at Test$Consumer.start(Test.java:46)
at Test.main(Test.java:31)

为什么我无法“重新启动”执行器或者如何实现此目的?

提前致谢!

最佳答案

Documentation

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted

因此,在修改 JDK 代码之前,无法重新启动。

关于java - 启动先前关闭的 ExecutorService 时出现 RejectedExecutionException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785292/

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