gpt4 book ai didi

java - 我们需要在 ScheduledExecutorService 上调用 awaitTermination 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:03 30 4
gpt4 key购买 nike

我是 Java 多线程的新手。我有数以千计的计划任务/线程需要执行。我正在使用以下代码:

ScheduledExecutorSerivce scheduleService = Executors.newScheduledThreadPool(90);
Map<Interger,Interger> loginMap = new HashMap<>();//contain login time of scheduled threads
for(int i = 0; i < taskCount ; i++) {
scheduleService.schedule(new MyCallableWorker(),loginMap.get(i),TimeUnit.SECONDS)
}
scheduleService.shutdown();
//do I need to call the following because I dont know any timeout value or above shutDown() is enough
while(!scheduleService.isTerminated()) {
}

另外请让我知道线程池的理想数量应该是多少。我已设置为 90,但我希望池可以根据需要增长,但看起来 ScheduleExecutorService 没有这样的 API。

最佳答案

scheduleService.shutdown();

将指示调度程序它不应该接受新任务,现有任务将被取消或可能会执行(但不会重复),具体取决于所使用的策略:

"If the ExecuteExistingDelayedTasksAfterShutdownPolicy has been set false, existing delayed tasks whose delays have not yet elapsed are cancelled. And unless the ContinueExistingPeriodicTasksAfterShutdownPolicy has been set true, future executions of existing periodic tasks will be cancelled."

现在在你的代码中你应该调用:

scheduleSerice.awaitTermination()

而不是 while(!scheduleService.isTerminated())。 while 循环将消耗处理器的所有周期,因为它将不断检查执行程序状态。

如果您不调用 awaitTermination 方法(或您的循环方法),您调用 shceduleService.schedule 的方法将简单地完成(退出),并且您的整个程序可能会终止(没有完成作业)。

但这取决于你的设计。如果它是异步的,那么您可以简单地忽略等待终止并继续您的工作。作业将在后台处理。

你的线程池不应该增长!!!! 它应该匹配你的可用资源 == CPU。对于等待资源的非 IO 任务,它应该围绕处理器数量,对于 IO 任务,CPU 数量加倍,任何更多都没有意义,它实际上会减慢执行速度,因为会有线程节流。

池大小限制了同时执行的任务数量,而不是任务队列的大小,除非另外设置,否则任务队列是无限增长的。

关于java - 我们需要在 ScheduledExecutorService 上调用 awaitTermination 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29544067/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com