wal*_*ers 15 java scheduler scheduled-tasks
我正在使用ScheduledExecutorService,在我调用它的shutdown方法之后,我无法在其上安排Runnable.抛出java.util.concurrent.RejectedExecutionException scheduleAtFixedRate(runnable, INITIAL_DELAY,
INTERVAL, TimeUnit.SECONDS)后调用shutdown().shutdown()在ScheduledExecutorService上调用之后是否有另一种方法来运行新任务?
Ale*_*ean 42
您可以重用调度程序,但不应该关闭它.而是取消在调用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()
Run Code Online (Sandbox Code Playgroud)
javadocs shutdown()说:
Initiates an orderly shutdown in which previously submitted tasks are executed,
but no new tasks will be accepted.
Run Code Online (Sandbox Code Playgroud)
因此,您无法调用shutdow()然后安排新任务.