gpt4 book ai didi

java - 如何使Java executor具有相同的线程?

转载 作者:行者123 更新时间:2023-12-03 12:54:09 24 4
gpt4 key购买 nike

对于某些建议,我需要创建一个始终具有相同线程的Executor

Executors.newFixedThreadPool(1);
Executors.newScheduledThreadPool(1);

上面的示例创建了一个线程池,但是当工作完成后,该线程将结束,如果将新任务传递给执行者,则会再次创建一个新的线程池。

所以我想出了像这样的东西:
new ThreadPoolExecutor(1,1,Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<>());

似乎可行,但我怀疑这是否是正确的方法。有人可以显示更好/正确的方法吗?

最佳答案

Executors.newSingleThreadExecutor();

the documentation(重点是我):

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

关于java - 如何使Java executor具有相同的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312548/

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