计划执行器服务启动停止数次

2022-09-02 19:15:52

我正在使用 ScheduledExecutorService,在我调用它的 shutdown 方法后,我无法在其上安排 Runnable。在抛出 java.util.concurrent.RejectedExecutionException 之后调用。在 ScheduledExecutorService 上调用后,是否有另一种方法可以运行新任务?scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)shutdown()shutdown()


答案 1

您可以重用调度程序,但不应将其关闭。相反,取消在调用 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()

答案 2

shutdown() 的 javadocs 说:

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

因此,您无法调用然后计划新任务。shutdow()


推荐