[英]ScheduledExecutorService start stop several times
我正在使用ScheduledExecutorService ,在我調用它的shutdown方法之后,我無法在其上安排Runnable。 在shutdown()
之后調用scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
shutdown()
拋出java.util.concurrent.RejectedExecutionException。 在ScheduledExecutorService上調用shutdown()
之后是否有另一種方法來運行新任務?
您可以重用調度程序,但不應該關閉它。 而是取消在調用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()
shutdown()
的javadocs說:
Initiates an orderly shutdown in which previously submitted tasks are executed,
but no new tasks will be accepted.
因此,您無法調用shutdow()
然后安排新任務。
關閉后,您無法讓執行者接受新任務。 更相關的問題是為什么你需要首先關閉它? 您創建的執行程序應在應用程序或子系統的整個生命周期內重復使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.