java - 如何让java执行器具有相同的线程?

标签 java multithreading threadpool executorservice

对于某些建议,我需要创建一个始终具有相同线程的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执行器具有相同的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312548/

相关文章:

c# - 当有工作要做时挂起并通知线程

java - Java中如何让ThreadPoolExecutor立即执行

python - 在进行网络编程时,是否有经验法则来确定使用多少个线程?

java - 哪些 Java 的哈希结构支持 'linear chaining' ?

Java调整堆大小问题

java - 匿名类实例中使用的未引用对象不会过期吗?

nhibernate - 每个线程的 NHibernate session 是否与线程池一起使用?

java - 在 jasper 报告中显示非常大的图像

java - 如何在 Android 上使用 HttpsURLConnection 和 HttpResponseCache 强制缓存?

c# - 如何在工作线程中从 UI 线程获取变量?