java ThreadPoolExecutor 拒绝的未来任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35338201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Future Task rejected from ThreadPoolExecutor
提问by MMPgm
I have a ThreadPoolExecutor
and I submit a task to it.
我有一个ThreadPoolExecutor
,我向它提交了一个任务。
private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
This code submits the Runnable
to the ThreadPoolExecutor
.
此代码将 提交Runnable
给ThreadPoolExecutor
.
protected void waitAndSweep(final String symbol) {
runnable = new Runnable() {
public void run() { /* irrelevant code */ }
};
try {
Future<?> self = threadPoolExecutor.submit(runnable);
futures.add(self);
} catch (RejectedExecutionException re) {
/* this exception will be thrown when wait and sweep is called more than twice.
* threadPoolExecutor can have one running task and one waiting task.
*/
} catch (Exception e) {
logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol, "Exception caught...", e);
}
}
The following code stops the task.
以下代码停止任务。
protected synchronized void stop(StrategyEntry entry) throws Exception {
for (Object future : futures) {
((Future<?>) future).cancel(true);
}
futures.clear();
threadPoolExecutor.shutdown();
}
The problem here is: When I try to stop the task, I am getting following exception:
这里的问题是:当我尝试停止任务时,出现以下异常:
Task java.util.concurrent.FutureTask@3a475611 rejected from java.util.concurrent.ThreadPoolExecutor@216393fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
任务 java.util.concurrent.FutureTask@3a475611 被 java.util.concurrent.ThreadPoolExecutor@216393fb 拒绝[已终止,池大小 = 0,活动线程 = 0,排队任务 = 0,已完成任务 = 1]
回答by RAnders00
The problem is that you shutdown()
the excutor in the stop method. If you just want to wait for the task to complete, use Future.get()
. When a executor is shut down, tasks can no longer be submitted to it.
问题是你shutdown()
是 stop 方法中的执行者。如果您只想等待任务完成,请使用Future.get()
. 当一个 executor 被关闭时,任务不能再提交给它。
shutdown()
should only be used when you actually want to terminate the application.
shutdown()
只应在您真正想要终止应用程序时使用。