对于某些建议,我需要创建一个始终具有相同线程的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 equivalentnewFixedThreadPool(1)
the returned executor is guaranteed not to be reconfigurable to use additional threads.
关于java - 如何让java执行器具有相同的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312548/