问题描述
我想在整个应用程序中使用相同的线程池.为此,我可以将ExecutorService
设置为静态和全局,以便在需要时可以调用ThreadUtil.executorService
来获取ExecutorService
.
I want to use the same thread pool throughout my application. To this end, I can make ExecutorService
static and global so that I can invoke ThreadUtil.executorService
to get ExecutorService
when I need it.
public class ThreadUtil {
public static final ExecutorService executorService = Executors.newCachedThreadPool();
}
这样可以实例化多个线程池吗?
Is it OK to instance multiple thread pools like this?
此外,我的应用程序是一个TCP服务器.如果我不知道池应该有多大,可以简单地使用newCachedThreadPool
吗?
In addition, my application is a TCP server. If I don't know how big the pool should be, is it ok to simply use newCachedThreadPool
?
推荐答案
当要在程序中的任何地方使用具有相同属性的实例时,逻辑上将其声明为static和final而不是重新创建该实例是合乎逻辑的时间,但我个人会选择Singleton模式,而不是直接向实例提供公共访问权限.
When an instance with the same properties is to be used anywhere in your program, it is logical to declare it static and final instead of re-creating the instance each time but I would personally opt for a Singleton pattern instead of directly giving public access to the instance.
对于您的第二个查询,我认为没有任何问题. newCachedThreadPool
文档的第一句话说
As for your second query, I don't see any problem with it. The first sentence of the documentation for newCachedThreadPool
says
由于您不知道将创建多少个线程,因此这是最合乎逻辑的选择.
since you don't know how many threads will be created, this is the most logical choice.
请注意,newCachedThreadPool
将在可用旧线程以提高性能时重新使用它们.
Note that newCachedThreadPool
will re-use old threads when they are available to increase performance.
这篇关于ExecutorService应该是静态的还是全局的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!