“`” 在《阿里巴巴 Java 开发手册》“并发处理”这一章节,明确指出线程资源必须通过线程池提供,不允许在应用中自行显示创建线程。

<strong>为什么呢?</strong>

<blockquote><strong>使用线程池的好处是减少在创建和销毁线程上所消耗的时间以及系统资源开销,解决资源不足的问题。如果不使用线程池,有可能会造成系统创建大量同类线程而导致消耗完内存或者“过度切换”的问题。</strong></p></blockquote>

<p><strong>另外《阿里巴巴 Java 开发手册》中强制线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 构造函数的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险</strong>

<blockquote>Executors 返回线程池对象的弊端如下:</p><ul><li><strong><code>FixedThreadPool</code> 和 <code>SingleThreadExecutor</code></strong> : 允许请求的队列长度为 Integer.MAX_VALUE,可能堆积大量的请求,从而导致 OOM。</li><li><strong>CachedThreadPool 和 ScheduledThreadPool</strong> : 允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。</li></ul></blockquote>

<p><strong>方式一:通过<code>ThreadPoolExecutor</code>构造函数实现(推荐)</strong><img alt=""通过构造方法实现"" src=""https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzE3ODU4MjMwLmpwZw?x-oss-process=image/format,png"" style=""width: 100%;""><strong>方式二:通过 Executor 框架的工具类 Executors 来实现</strong>我们可以创建三种类型的 ThreadPoolExecutor:

<ul><li><strong>FixedThreadPool</strong></li><li><strong>SingleThreadExecutor</strong></li><li><strong>CachedThreadPool</strong></li></ul>

对应 Executors 工具类中的方法如图所示:<img alt=""通过Executor 框架的工具类Executors来实现"" src=""https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzEzMjk2OTAxLmpwZw?x-oss-process=image/format,png"" style=""width: 100%;"">

<pre><code> "“`

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.