我的代码是这样的:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(8);
//complex code that call this multiple times too add tasks:
executor.schedule(() -> { doRealTask(); }, 0, TimeUnit.MICROSECONDS);
//drain the pool on some condition, e.g. meets tasks that can't be parallelized:
executor.shutdown();//without this, awaitTermination won't return since all the threads in the pool will be paused, not terminated
executor.awaitTermination(1000000, TimeUnit.SECONDS);
//continue to add more tasks:
executor.schedule(...);
最后一个代码抛出 java.util.concurrent.RejectedExecutionException 。原因似乎是执行器已关闭。但没有“startAgain”功能。显然创建一个新的 ScheduledExecutorService 是有效的,但我觉得我使用了错误的解决方案。
如何在Java中实现这个?
三国纷争
心有法竹
相关分类