Executors.newFixedThreadPool(1) 和 Executors.newSingleThreadExecutor()

2022-09-01 17:36:40

我的问题是:使用是否有意义。在两个线程(主线程 + 一个另一个线程)方案中,使用执行器服务是否有效?通过调用直接创建新线程是否比使用 ExecutorService 更好?在此类场景中使用 ExecutorService 有哪些优点和缺点?Executors.newFixedThreadPool(1)??new Runnable(){ }

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

我已经了解了:使用执行器服务有什么好处?并且一次只能有一个线程!


答案 1

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

它本质上与 a 是一回事,只是后者是不可重配置的,如 javadoc 中所示,而前者是如果你把它强制转换为 .Executors.newSingleThreadExecutor()ThreadPoolExecutor

在两个线程(主线程 + 一个另一个线程)方案中,使用执行器服务是否有效?

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

在任何最现实的生活中,监视任务生命周期的可能性(通过返回的s),执行程序将在未捕获的异常情况下根据需要重新创建线程的事实,回收线程与创建新线程的性能提升等,使执行程序服务成为更强大的解决方案,只需很少的额外成本。Future

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

Executors.newSingleThreadExecutor().execute(command) 和 new Thread(command).start();通过两个选项之间的微小行为差异。


答案 2

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

private final ExecutorService executor = Executors.newFixedThreadPool(1);

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