ExecutorService应该是静态的还是全局的

编程入门 行业动态 更新时间:2024-10-22 19:22:47
本文介绍了ExecutorService应该是静态的还是全局的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在整个应用程序中使用相同的线程池.为此,我可以将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

创建一个线程池,该线程池根据需要创建新线程

Creates a thread pool that creates new threads as needed

由于您不知道将创建多少个线程,因此这是最合乎逻辑的选择.

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应该是静态的还是全局的

本文发布于:2023-11-15 21:24:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598075.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   静态   应该是   ExecutorService

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!