【发布时间】:2019-10-11 13:40:23
【问题描述】:
我的代码是这样的:
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 在最后一个代码上抛出。原因似乎是 executor 已关闭。但是没有“startAgain”功能。显然创建一个新的 ScheduledExecutorService 是可行的,但我觉得我使用了错误的解决方案。
如何在 Java 中实现?
【问题讨论】:
-
为什么不使用调用 schedule 时返回的期货?您可以将它们存储在列表中并循环它们,然后使用 .get 实质上加入您的任务。
-
你到底想做什么?
-
@tmarwen 将大量任务发送到池中由多个线程执行,当遇到一些无法并行化的任务时,先等待前一个任务完成然后将其发送到池中。