Executors.newFixedThreadPool(1)和Executors.newSingleThreadExecutor()之间的区别 [英] Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()
问题描述
我的问题是:使用 Executors.newFixedThreadPool(1)??
是否有意义。在两个线程(main + oneAnotherThread)场景中,使用执行程序服务是否有效?是否通过调用 new Runnable(){}
直接创建新线程比使用ExecutorService更好?在这种情况下使用ExecutorService有什么好处和缺点?
My question is : 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?. What are the upsides and downsides of using ExecutorService for such scenarios?
PS:主线程和oneAnotherThread不访问任何公共资源。
PS: Main thread and oneAnotherThread dont access any common resource(s).
我已经完成了:什么是使用ExecutorService的优势?。和一次只有一个主题!
推荐答案
使用
Executors.newFixedThreadPool(1)
是否有意义?
它与 Executors.newSingleThreadExecutor()
基本相同后者不可重新配置,如 javadoc ,而前者是你将它转换为 ThreadPoolExecutor
。
It is essentially the same thing as an Executors.newSingleThreadExecutor()
except that the latter is not reconfigurable, as indicated in the javadoc, whereas the former is if you cast it to a ThreadPoolExecutor
.
在两个线程(main + oneAnotherThread)中,使用执行程序服务是否有效?
In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?
执行程序服务是围绕线程的非常薄的包装器,它极大地促进了线程生命周期管理。如果你唯一需要的是新的Thread(runnable).start();
并继续前进,那么就没有真正需要ExecutorService。
An executor service is a very thin wrapper around a Thread that significantly facilitates the thread lifecycle management. If the only thing you need is to new Thread(runnable).start();
and move on, then there is no real need for an ExecutorService.
在任何大多数现实生活中,监控任务生命周期的可能性(通过返回的 Future
),事实如果没有被捕获的异常,执行程序将根据需要重新创建线程,回收线程的性能增益与创建新线程等使得执行程序服务成为一个更加强大的解决方案,只需要很少的额外成本。
In any most real life cases, the possibility to monitor the life cycle of the tasks (through the returned Future
s), the fact that the executor will re-create threads as required in case of uncaught exceptions, the performance gain of recycling threads vs. creating new ones etc. make the executor service a much more powerful solution at little additional cost.
底线:我没有看到使用执行程序服务与线程的任何缺点。
Bottom line: I don't see any downsides of using an executor service vs. a thread.
Executors.newSingleThreadExecutor()。执行(命令)和新线程(命令).start(); 之间的差异经历了行为之间的微小差异两个选项。
The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start(); goes through the small differences in behaviour between the two options.
这篇关于Executors.newFixedThreadPool(1)和Executors.newSingleThreadExecutor()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!