java - singlethreadexecutor - 多线程 java

标签 java multithreading concurrency operating-system

什么时候应该在 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/

相关文章:

c++ - asio::async_write 和 strand

java - ThreadPoolExecutor 同步

java - Android KeyStore : Failed to generate self-signed certificate , 无效的日期字符串

java - 如何摆脱 try/catch block 的 IOException 捕获上的 IntelliJ 警告/错误?

java - 元音计数代码问题

java - 守护线程在生产者消费者中如何工作?无法让它工作

multithreading - 操作系统 : Creating a thread in a screensaver

java - AspectJ 切入点匹配参数 (args()) 未正确匹配

Java同步块(synchronized block)使用方法调用获取同步对象

java - 应用中存在一个生产者多个消费者时apache kafka如何处理一致性