我需要运行五个线程每 20 秒重复从 API 获取数据,所以我使用了 ScheduledExecutorService。
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 5; i++) {
scheduler.scheduleWithFixedDelay(Constant.workerThread[i], 0, delay, TimeUnit.SECONDS);
}
我如何知道(每次)五个线程何时执行?
最佳答案
编辑:看来人们并没有真正理解代码片段的概念。我会把它加粗,这样就不会再有人来找我了,管理内心ExecutorService
在外部,不在 Callable
内部lambda,在需要时采取适当的措施有序关闭它。
您可以做的是管理一个计划任务,并在该任务中执行您的五个工作人员。
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
scheduler.scheduleWithFixedDelay(
() -> {
final ExecutorService e = Executors.newFixedThreadPool(5);
final CompletionService<?> cs = new ExecutorCompletionService<>(e);
for (int i = 0; i < 5; i++) {
// Constant.workerThread[i] is a Runnable
cs.submit(Constant.workerThread[i], null);
}
for (int i = 0; i < 5; i++) {
try {
// Will block until a Future<?> result is available.
// Doesn't matter which one, it will take the first available.
cs.take();
} catch (final InterruptedException ignored) {
// Ingore the exception, as we care only
// about if all off them finished (abruptly or not)
}
}
// All of them finished!
e.shutdown();
}, 0, 20, TimeUnit.SECONDS));
JavaDoc ExecutorCompletionService
A
CompletionService
that uses a suppliedExecutor
to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible usingtake
.
JavaDoc ExecutorCompletionService#take
Retrieves and removes the
Future
representing the next completed task, waiting if none are yet present.
这必须改进,但你应该明白了。
关于java - 如何知道 Runnable 被安排重复执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071972/