关于java:Executors.newFixedThreadPool(1)和Executors.newSingleThreadExecutor()之间的区别

Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()

我的问题是:使用Executors.newFixedThreadPool(1)??是否有意义。 在两个线程(main + oneAnotherThread)中,使用执行程序服务是否有效? 通过调用new Runnable(){ }直接创建新线程是否比使用ExecutorService更好? 在这种情况下使用ExecutorService有什么好处和坏处?

PS:主线程和oneAnotherThread不访问任何公共资源。

我经历了:使用ExecutorService有什么优势? 一次只能有一个线程!


does it make sense to use Executors.newFixedThreadPool(1)?

它与Executors.newSingleThreadExecutor()本质上是相同的,不同之处在于后者是不可重新配置的(如javadoc中所示),而前者是将其强制转换为ThreadPoolExecutor的情况。

In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?

执行程序服务是围绕线程的非常薄的包装器,可显着促进线程生命周期管理。如果您唯一需要的是new Thread(runnable).start();并继续前进,则不需要ExecutorService。

在任何现实生活中,都有可能监视任务的生命周期(通过返回的Future),执行者将在未捕获的异常情况下根据需要重新创建线程的事实,回收的性能收益线程与创建新线程等比较,使执行程序服务成为功能更强大的解决方案,而无需支付额外的费用。

底线:我看不到使用执行程序服务和线程的任何缺点。

Executors.newSingleThreadExecutor()。execute(command)和new Thread(command).start();之间的区别经历了两个选项之间行为上的细微差异。


does it make sense to use Executors.newFixedThreadPool(1)??

是。如果您要按到达顺序处理所有已提交的任务,这很有意义

In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service? Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?.

我更喜欢ExecutorServiceThreadPoolExecutor,即使是1个线程。

请参阅以下SE问题以获取ThreadPoolExecutor相对于新Runnable()的优势的解释:

ExecutorService与Casual Thread Spanner

What are the upsides and downsides of using ExecutorService for such scenarios?

看看与ExexutorService用例有关的SE问题:

Javas Fork / Join与ExecutorService-什么时候使用?

关于主题行中的查询(来自grepcode),两者相同:

newFixedThreadPool API将返回ThreadPoolExecutor作为ExecutorService:

1
2
3
4
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());

newSingleThreadExecutor()返回ThreadPoolExecutor作为ExecutorService:

1
2
3
4
5
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));

我同意@assylias关于相似性/差异性的答案。


有时需要使用Executors.newFixedThreadPool(1)确定队列中的任务数

1
2
3
4
5
6
private final ExecutorService executor = Executors.newFixedThreadPool(1);

public int getTaskInQueueCount() {
    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
    return threadPoolExecutor.getQueue().size();
}

通过调用new Runnable(){}直接创建新线程是否比使用ExecutorService更好?

如果要在线程编译后对返回的结果进行计算,则可以使用Callable接口,该接口只能与ExecutorService一起使用,而不能与new Runnable(){}一起使用。 ExecutorService的Submit()方法以Callable对象为依据,它返回Future对象。在此Future对象上,如果不使用isDone()方法,则检查任务是否已完成。您也可以使用get()方法获得结果。
在这种情况下,ExecutorService优于新的Runnable(){}。