Executors.newFixedThreadPool(1)和Executors.newSingleThreadExecutor()之间的区别

时间:2014-01-23 06:27:17

标签: java multithreading executor

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

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

我经历过:What are the advantages of using an ExecutorService?。和Only one thread at a time!

4 个答案:

答案 0 :(得分:13)

  

使用Executors.newFixedThreadPool(1)是否有意义?

它与Executors.newSingleThreadExecutor()基本相同,只是后者不可重新配置,如javadoc所示,而前者则是将其转换为ThreadPoolExecutor

  

在两个线程(main + oneAnotherThread)中,使用执行程序服务是否有效?

执行程序服务是一个非常薄的线程包装器,它极大地方便了线程生命周期管理。如果您唯一需要的是new Thread(runnable).start();并继续前进,那么就不需要ExecutorService。

在任何大多数现实生活中,监视任务生命周期的可能性(通过返回的Future),执行者将在未捕获的异常情况下根据需要重新创建线程,回收线程的性能提升与创建新线程等使得执行器服务成为一个更加强大的解决方案,而且成本很低。

结论:我没有看到使用执行程序服务与线程的任何缺点。

The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start();经历了两个选项之间行为的微小差异。

答案 1 :(得分:1)

有时需要使用strncat()来确定队列中的任务数量

Executors.newFixedThreadPool(1)

答案 2 :(得分:1)

  

使用Executors.newFixedThreadPool(1)??

是否有意义

是。这是有道理的如果您想按到达顺序处理所有提交的任务

  

在两个线程(main + oneAnotherThread)中,使用执行程序服务是否有效?通过调用new Runnable(){}直接创建一个新线程比使用ExecutorService更好吗?

我更喜欢ExecutorServiceThreadPoolExecutor,即使是1个帖子。

请参阅下面的SE问题,了解ThreadPoolExecutor优于新Runnable()的优势:

ExecutorService vs Casual Thread Spawner

  

在这种情况下使用ExecutorService有哪些好处和缺点?

查看有关ExexutorService用例的相关SE问题:

Java's Fork/Join vs ExecutorService - when to use which?

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

newFixedThreadPool API会将ThreadPoolExecutor作为ExecutorService返回:

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

newSingleThreadExecutor()将ThreadPoolExecutor作为ExecutorService返回:

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

我同意@assylias关于相似/不同的答案。

答案 3 :(得分:0)

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

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

相关问题