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

How to have java executor with same thread?

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

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

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

所以我想到了这样的事情:

new ThreadPoolExecutor(1,1,Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<>());

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

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.