gpt4 book ai didi

java - singlethreadexecutor - 多线程 java

转载 作者:行者123 更新时间:2023-11-30 10:50:04 25 4
gpt4 key购买 nike

什么时候应该在 java 中使用 singleThreadExecutor?另外,什么时候应该使用缓存线程池?在文档和书籍中都指定了 singleThreadExecutor 优于 fixedThreadPool(1),因为它不允许像后者那样修改线程数,但是在什么情况下建议或使用 singleThreadExecutor

最佳答案

newSingleThreadExecutor() 当您知道一个额外的线程在后台执行作业就足够了(这意味着不会有很多作业在队列中等待)时,这很好。你不需要/不想扩展 Thread 或实现 Runnable 并自己完成所有传输工作。 Tasks are guaranteed to execute sequentially - 如果您知道并行任务执行可能导致死锁或数据竞争,这也可能很有用。

cachedThreadpool() - 只需查看源代码

public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

它按需创建新线程并让它们空闲不超过 1 分钟。正如文档中所说

.. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. ..

但是线程数没有上限,所以我更愿意用 maximumPoolSizeInteger.MAX_VALUE 少得多的手工构造池,例如128.

关于java - singlethreadexecutor - 多线程 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35190471/

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