16

I am using ScheduledExecutorService, and after I call it's shutdown method, I can't schedule a Runnable on it. Calling scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) after shutdown() throws java.util.concurrent.RejectedExecutionException. Is there another way to run a new task after shutdown() is called on ScheduledExecutorService?

4

3 回答 3

48

您可以重用调度程序,但不应关闭它。相反,取消调用 scheduleAtFixedRate 方法时可以获得的正在运行的线程。前任:

//get reference to the future
Future<?> future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//cancel instead of shutdown
future.cancel(true);
//schedule again (reuse)
future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//shutdown when you don't need to reuse the service anymore
service.shutdown()
于 2011-10-24T16:49:47.250 回答
6

The javadocs of shutdown() say:

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

So, you cannot call shutdow() and then schedule new tasks.

于 2010-11-17T14:29:35.023 回答
2

你不能让你的执行者在关闭它后接受新的任务。更相关的问题是为什么首先需要将其关闭?您创建的执行程序应该在您的应用程序或子系统的整个生命周期内重复使用。

于 2011-10-24T17:02:35.883 回答