1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-16 18:10:13 +08:00

线程池详解

This commit is contained in:
Kou Shuang 2019-11-13 11:28:04 +08:00
parent 3bfa5637f0
commit 87009c475f
15 changed files with 515 additions and 164 deletions

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -0,0 +1,49 @@
package callable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static common.ThreadPoolConstants.CORE_POOL_SIZE;
import static common.ThreadPoolConstants.KEEP_ALIVE_TIME;
import static common.ThreadPoolConstants.MAX_POOL_SIZE;
import static common.ThreadPoolConstants.QUEUE_CAPACITY;
public class CallableDemo {
public static void main(String[] args) {
//使用阿里巴巴推荐的创建线程池的方式
//通过ThreadPoolExecutor构造函数自定义参数创建
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
List<Future<String>> futureList = new ArrayList<>();
Callable<String> callable = new MyCallable();
for (int i = 0; i < 10; i++) {
//提交任务到线程池
Future<String> future = executor.submit(callable);
//将返回值 future 添加到 list我们可以通过 future 获得 执行 Callable 得到的返回值
futureList.add(future);
}
for (Future<String> fut : futureList) {
try {
System.out.println(new Date() + "::" + fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
//关闭线程池
executor.shutdown();
}
}

View File

@ -0,0 +1,13 @@
package callable;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
//返回执行当前 Callable 的线程名字
return Thread.currentThread().getName();
}
}

View File

@ -0,0 +1,11 @@
package common;
public class ThreadPoolConstants {
public static final int CORE_POOL_SIZE = 5;
public static final int MAX_POOL_SIZE = 10;
public static final int QUEUE_CAPACITY = 100;
public static final Long KEEP_ALIVE_TIME = 1L;
private ThreadPoolConstants(){
}
}

View File

@ -1,14 +1,16 @@
package threadPoolExecutor;
import java.util.Date;
/**
* 这是一个简单的Runnable类需要大约5秒钟来执行其任务
* @author shuang.kou
*/
public class WorkerThread implements Runnable {
public class MyRunnable implements Runnable {
private String command;
public WorkerThread(String s) {
public MyRunnable(String s) {
this.command = s;
}

View File

@ -1,14 +1,17 @@
package threadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorDemo {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
import static common.ThreadPoolConstants.CORE_POOL_SIZE;
import static common.ThreadPoolConstants.KEEP_ALIVE_TIME;
import static common.ThreadPoolConstants.MAX_POOL_SIZE;
import static common.ThreadPoolConstants.QUEUE_CAPACITY;
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
//使用阿里巴巴推荐的创建线程池的方式
@ -23,7 +26,7 @@ public class ThreadPoolExecutorDemo {
for (int i = 0; i < 10; i++) {
//创建WorkerThread对象WorkerThread类实现了Runnable 接口
Runnable worker = new WorkerThread("" + i);
Runnable worker = new MyRunnable("" + i);
//执行Runnable
executor.execute(worker);
}

View File

@ -355,25 +355,79 @@ ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
### 4.1. 为什么要用线程池?
线程池提供了一种限制和管理资源(包括执行一个任务)。 每个线程池还维护一些基本统计信息,例如已完成任务的数量。
> **池化技术相比大家已经屡见不鲜了线程池、数据库连接池、Http 连接池等等都是对这个思想的应用。池化技术的思想主要是为了减少每次获取资源的消耗,提高对资源的利用率。**
这里借用《Java并发编程的艺术》提到的来说一下使用线程池的好处
**线程池**提供了一种限制和管理资源(包括执行一个任务)。 每个**线程池**还维护一些基本统计信息,例如已完成任务的数量。
- **降低资源消耗。** 通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
- **提高响应速度。** 当任务到达时,任务可以不需要的等到线程创建就能立即执行。
- **提高线程的可管理性。** 线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
这里借用《Java 并发编程的艺术》提到的来说一下**使用线程池的好处**
- **降低资源消耗**。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
- **提高响应速度**。当任务到达时,任务可以不需要的等到线程创建就能立即执行。
- **提高线程的可管理性**。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
### 4.2. 实现Runnable接口和Callable接口的区别
如果想让线程池执行任务的话需要实现的Runnable接口或Callable接口。 Runnable接口或Callable接口实现类都可以被ThreadPoolExecutor或ScheduledThreadPoolExecutor执行。两者的区别在于 Runnable 接口不会返回结果但是 Callable 接口可以返回结果
`Runnable`自Java 1.0以来一直存在,但`Callable`仅在Java 1.5中引入,目的就是为了来处理`Runnable`不支持的用例。**`Runnable` 接口**不会返回结果或抛出检查异常,但是**`Callable` 接口**可以。所以,如果任务不需要返回结果或抛出异常推荐使用 **`Runnable` 接口**,这样代码看起来会更加简洁
**备注:** 工具类`Executors`可以实现`Runnable`对象和`Callable`对象之间的相互转换。(`Executors.callableRunnable task``Executors.callableRunnable taskObject resule`)。
工具类 `Executors` 可以实现 `Runnable` 对象和 `Callable` 对象之间的相互转换。(`Executors.callableRunnable task`)或 `Executors.callableRunnable taskObject resule`)。
`Runnable.java`
```java
@FunctionalInterface
public interface Runnable {
/**
* 被线程执行,没有返回值也无法抛出异常
*/
public abstract void run();
}
```
`Callable.java`
```java
@FunctionalInterface
public interface Callable<V> {
/**
* 计算结果,或在无法这样做时抛出异常。
* @return 计算得出的结果
* @throws 如果无法计算结果,则抛出异常
*/
V call() throws Exception;
}
```
### 4.3. 执行execute()方法和submit()方法的区别是什么呢?
1)**`execute()` 方法用于提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功与否;**
1. **`execute()`方法用于提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功与否;**
2. **`submit()`方法用于提交需要返回值的任务。线程池会返回一个 `Future` 类型的对象,通过这个 `Future` 对象可以判断任务是否执行成功**,并且可以通过 `Future``get()`方法来获取返回值,`get()`方法会阻塞当前线程直到任务完成,而使用 `getlong timeoutTimeUnit unit`方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完。
2)**`submit()` 方法用于提交需要返回值的任务。线程池会返回一个Future类型的对象通过这个Future对象可以判断任务是否执行成功**并且可以通过future的get()方法来获取返回值get()方法会阻塞当前线程直到任务完成,而使用 `getlong timeoutTimeUnit unit`方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完。
我们以**`AbstractExecutorService`**接口中的一个 `submit` 方法为例子来看看源代码:
```java
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
```
上面方法调用的 `newTaskFor` 方法返回了一个 `FutureTask` 对象。
```java
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
```
我们再来看看`execute()`方法:
```java
public void execute(Runnable command) {
...
}
```
### 4.4. 如何创建线程池

View File

@ -1,44 +1,6 @@
<!-- TOC -->
- [一 使用线程池的好处](#一-使用线程池的好处)
- [二 Executor 框架](#二-executor-框架)
- [2.1 简介](#21-简介)
- [2.2 Executor 框架结构(主要由三大部分组成)](#22-executor-框架结构主要由三大部分组成)
- [1 任务。](#1-任务)
- [2 任务的执行](#2-任务的执行)
- [3 异步计算的结果](#3-异步计算的结果)
- [2.3 Executor 框架的使用示意图](#23-executor-框架的使用示意图)
- [三 ThreadPoolExecutor 类简单介绍(重要)](#三-threadpoolexecutor-类简单介绍重要)
- [3.1 ThreadPoolExecutor 类分析](#31-threadpoolexecutor-类分析)
- [3.2 推荐使用ThreadPoolExecutor 构造函数创建线程池](#32-推荐使用threadpoolexecutor-构造函数创建线程池)
- [四 ThreadPoolExecutor 使用示例](#四-threadpoolexecutor-使用示例)
- [4.1 示例代码](#41-示例代码)
- [4.2 原理分析](#42-原理分析)
- [4.3 几个常见的方法对比](#43-几个常见的方法对比)
- [4.3.1 shutdownVS shutdownNow](#431-shutdownvs-shutdownnow)
- [4.3.2 isTerminated() Vs isShutdown()](#432-isterminated-vs-isshutdown)
- [五 几种常见的线程池详解](#五-几种常见的线程池详解)
- [5.1 FixedThreadPool 详解](#51-fixedthreadpool-详解)
- [5.2 SingleThreadExecutor 详解](#52-singlethreadexecutor-详解)
- [5.3 CachedThreadPool 详解](#53-cachedthreadpool-详解)
- [六 ScheduledThreadPoolExecutor 详解](#六-scheduledthreadpoolexecutor-详解)
- [6.1 简介](#61-简介)
- [6.2 运行机制](#62-运行机制)
- [6.3 ScheduledThreadPoolExecutor 执行周期任务的步骤](#63-scheduledthreadpoolexecutor-执行周期任务的步骤)
- [6.4 ScheduledThreadPoolExecutor 使用示例](#64-scheduledthreadpoolexecutor-使用示例)
- [6.4.1 ScheduledExecutorService scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit)方法](#641-scheduledexecutorservice-scheduleatfixedraterunnable-commandlong-initialdelaylong-periodtimeunit-unit方法)
- [6.4.2 ScheduledExecutorService scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)方法](#642-scheduledexecutorservice-schedulewithfixeddelayrunnable-commandlong-initialdelaylong-delaytimeunit-unit方法)
- [6.4.3 scheduleWithFixedDelay() vs scheduleAtFixedRate()](#643-schedulewithfixeddelay-vs-scheduleatfixedrate)
- [七 各种线程池的适用场景介绍](#七-各种线程池的适用场景介绍)
- [八 总结](#八-总结)
- [九 参考](#九-参考)
- [十 其他推荐阅读](#十-其他推荐阅读)
<!-- /TOC -->
## 一 使用线程池的好处
**池化技术相比大家已经屡见不鲜了线程池、数据库连接池、Http 连接池等等都是对这个思想的应用。池化技术的思想主要是为了减少每次获取资源的消耗,提高对资源的利用率。**
> **池化技术相比大家已经屡见不鲜了线程池、数据库连接池、Http 连接池等等都是对这个思想的应用。池化技术的思想主要是为了减少每次获取资源的消耗,提高对资源的利用率。**
**线程池**提供了一种限制和管理资源(包括执行一个任务)。 每个**线程池**还维护一些基本统计信息,例如已完成任务的数量。
@ -58,28 +20,26 @@ Executor 框架是 Java5 之后引进的,在 Java 5 之后,通过 Executor
### 2.2 Executor 框架结构(主要由三大部分组成)
#### 1 任务。
#### 1) 任务(`Runnable` /`Callable`)
执行任务需要实现的**Runnable 接口**或**Callable 接口**。**Runnable 接口**或**Callable 接口**实现类都可以被**ThreadPoolExecutor**或**ScheduledThreadPoolExecutor**执行。
执行任务需要实现的 **`Runnable` 接口** 或 **`Callable`接口**。**`Runnable` 接口**或 **`Callable` 接口** 实现类都可以被 **`ThreadPoolExecutor`** 或 **`ScheduledThreadPoolExecutor`** 执行。
**两者的区别:**
#### 2) 任务的执行(`Executor`)
> **Runnable 接口**不会返回结果但是**Callable 接口**可以返回结果。后面介绍**Executors 类**的一些方法的时候会介绍到两者的相互转换
如下图所示,包括任务执行机制的核心接口 **`Executor`** ,以及继承自 `Executor` 接口的 **`ExecutorService` 接口。`ThreadPoolExecutor`** 和 **`ScheduledThreadPoolExecutor`** 这两个关键类实现了 **ExecutorService 接口**
#### 2 任务的执行
**这里提了很多底层的类关系,但是,实际上我们需要更多关注的是 `ThreadPoolExecutor` 这个类,这个类在我们实际使用线程池的过程中,使用频率还是非常高的。**
如下图所示,包括任务执行机制的**核心接口 Executor** ,以及继承自 Executor 接口的**ExecutorService 接口**。**ThreadPoolExecutor** 和 **ScheduledThreadPoolExecutor**这两个关键类实现了**ExecutorService 接口**
> **注意:** 通过查看 `ScheduledThreadPoolExecutor` 源代码我们发现 `ScheduledThreadPoolExecutor` 实际上是继承了 `ThreadPoolExecutor` 并实现了 ScheduledExecutorService ,而 `ScheduledExecutorService` 又实现了 `ExecutorService`,正如我们下面给出的类关系图显示的一样
> **注意:** 通过查看 `ScheduledThreadPoolExecutor` 源代码我们发现 `ScheduledThreadPoolExecutor` 实际上是继承了 `ThreadPoolExecutor` 并实现了 ScheduledExecutorService ,而 `ScheduledExecutorService` 又实现了 ` ExecutorService`,正如我们下面给出的类关系图显示的一样。
**ThreadPoolExecutor 类描述:**
**`ThreadPoolExecutor` 类描述:**
```java
//AbstractExecutorService实现了ExecutorService接口
public class ThreadPoolExecutor extends AbstractExecutorService
```
**ScheduledThreadPoolExecutor 类描述:**
**`ScheduledThreadPoolExecutor` 类描述:**
```java
//ScheduledExecutorService实现了ExecutorService接口
@ -88,50 +48,26 @@ public class ScheduledThreadPoolExecutor
implements ScheduledExecutorService
```
![任务的执行相关接口](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzkwMDU4NTc0LmpwZw?x-oss-process=image/format,png)
![任务的执行相关接口](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/任务的执行相关接口.png)
#### 3 异步计算的结果
#### 3) 异步计算的结果(`Future`)
**Future 接口**以及 Future 接口的实现类**FutureTask 类**。
当我们把**Runnable 接口**或**Callable 接口**的实现类提交(调用 submit 方法)给**ThreadPoolExecutor**或**ScheduledThreadPoolExecutor**时,会返回一个**FutureTask 对象**。
**`Future`** 接口以及 `Future` 接口的实现类 **`FutureTask`** 类都可以代表异步计算的结果。
我们以**AbstractExecutorService**接口中的一个 submit 方法为例子来看看源代码:
```java
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
```
上面方法调用的 newTaskFor 方法返回了一个 FutureTask 对象。
```java
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
```
当我们把 **`Runnable`接口** 或 **`Callable` 接口** 的实现类提交给 **`ThreadPoolExecutor`** 或 **`ScheduledThreadPoolExecutor`** 执行。(调用 `submit()` 方法时会返回一个 **`FutureTask`** 对象)
### 2.3 Executor 框架的使用示意图
![Executor 框架的使用示意图](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC01LTMwLzg0ODIzMzMwLmpwZw?x-oss-process=image/format,png)
1. **主线程首先要创建实现 Runnable 或者 Callable 接口的任务对象。**
**备注:** 工具类 Executors 可以实现 Runnable 对象和 Callable 对象之间的相互转换。(`Executors.callableRunnable task`)或 `Executors.callableRunnable taskObject resule`)。
2. **然后可以把创建完成的 Runnable 对象直接交给 ExecutorService 执行**ExecutorService.executeRunnable command或者也可以把 Runnable 对象或 Callable 对象提交给 ExecutorService 执行ExecutorService.submitRunnable task或 ExecutorService.submitCallable <T> task
3. **如果执行 ExecutorService.submitExecutorService 将返回一个实现 Future 接口的对象**(我们刚刚也提到过了执行 `execute()`方法和 `submit()`方法的区别,到目前为止的 JDK 中,返回的是 FutureTask 对象)。由于 FutureTask 实现了 Runnable程序员也可以创建 FutureTask然后直接交给 `ExecutorService` 执行。
1. **主线程首先要创建实现 `Runnable` 或者 `Callable` 接口的任务对象。**
2. **把创建完成的实现 `Runnable`/`Callable`接口的 对象直接交给 `ExecutorService` 执行**: `ExecutorService.executeRunnable command`)或者也可以把 `Runnable` 对象或`Callable` 对象提交给 `ExecutorService` 执行(`ExecutorService.submitRunnable task``ExecutorService.submitCallable <T> task`)。
3. **如果执行 `ExecutorService.submit``ExecutorService` 将返回一个实现`Future`接口的对象**(我们刚刚也提到过了执行 `execute()`方法和 `submit()`方法的区别,`submit()`会返回一个 `FutureTask 对象)。由于 FutureTask` 实现了 `Runnable`,我们也可以创建 `FutureTask`,然后直接交给 `ExecutorService` 执行。
4. **最后,主线程可以执行 `FutureTask.get()`方法来等待任务执行完成。主线程也可以执行 `FutureTask.cancelboolean mayInterruptIfRunning`来取消此任务的执行。**
**执行 execute()方法和 submit()方法的区别是什么呢?**
## 三 (重要)ThreadPoolExecutor 类简单介绍
> 1. **execute()方法用于提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功与否;**
> 2. **submit()方法用于提交需要返回值的任务。线程池会返回一个 future 类型的对象,通过这个 future 对象可以判断任务是否执行成功**,并且可以通过 future 的 get()方法来获取返回值get()方法会阻塞当前线程直到任务完成,而使用 getlong timeoutTimeUnit unit方法则会阻塞当前线程一段时间后立即返回这时候有可能任务没有执行完。
## 三 ThreadPoolExecutor 类简单介绍(重要)
线程池实现类 ThreadPoolExecutor 是 Executor 框架最核心的类,先来看一下这个类中比较重要的四个属性
**线程池实现类 `ThreadPoolExecutor``Executor` 框架最核心的类。**
### 3.1 ThreadPoolExecutor 类分析
@ -166,7 +102,7 @@ public class ScheduledThreadPoolExecutor
**下面这些对创建 非常重要,在后面使用线程池的过程中你一定会用到!所以,务必拿着小本本记清楚。**
**`ThreadPoolExecutor` 3个最重要的参数**
**`ThreadPoolExecutor` 3 个最重要的参数:**
- **`corePoolSize` :** 核心线程数线程数定义了最小可以同时运行的线程数量。
- **`maximumPoolSize` :** 当队列中存放的任务达到队列容量的时候,当前可以同时运行的线程数量变为最大线程数。
@ -175,7 +111,7 @@ public class ScheduledThreadPoolExecutor
`ThreadPoolExecutor`其他常见参数:
1. **`keepAliveTime`**:当线程池中的线程数量大于 `corePoolSize` 的时候,如果这时没有新的任务提交,核心线程外的线程不会立即销毁,而是会等待,直到等待的时间超过了 `keepAliveTime`才会被回收销毁;
2. **`unit`** : `keepAliveTime` 参数的时间单位。
2. **`unit`** : `keepAliveTime` 参数的时间单位。
3. **`threadFactory`** :executor 创建新线程的时候会用到。
4. **`handler`** :饱和策略。关于饱和策略下面单独介绍一下。
@ -183,14 +119,14 @@ public class ScheduledThreadPoolExecutor
如果当前同时运行的线程数量达到最大线程数量并且队列也已经被放满了任时,`ThreadPoolTaskExecutor` 定义一些策略:
- **ThreadPoolExecutor.AbortPolicy**:抛出 `RejectedExecutionException`来拒绝新任务的处理。
- **ThreadPoolExecutor.CallerRunsPolicy**:调用执行自己的线程运行任务。您不会任务请求。但是这种策略会降低对于新任务提交速度,影响程序的整体性能。另外,这个策略喜欢增加队列容量。如果您的应用程序可以承受此延迟并且你不能任务丢弃任何一个任务请求的话,你可以选择这个策略。
- **ThreadPoolExecutor.DiscardPolicy** 不处理新任务,直接丢弃掉。
- **ThreadPoolExecutor.DiscardOldestPolicy** 此策略将丢弃最早的未处理的任务请求。
- **`ThreadPoolExecutor.AbortPolicy`**:抛出 `RejectedExecutionException`来拒绝新任务的处理。
- **`ThreadPoolExecutor.CallerRunsPolicy`**:调用执行自己的线程运行任务。您不会任务请求。但是这种策略会降低对于新任务提交速度,影响程序的整体性能。另外,这个策略喜欢增加队列容量。如果您的应用程序可以承受此延迟并且你不能任务丢弃任何一个任务请求的话,你可以选择这个策略。
- **`ThreadPoolExecutor.DiscardPolicy`** 不处理新任务,直接丢弃掉。
- **`ThreadPoolExecutor.DiscardOldestPolicy`** 此策略将丢弃最早的未处理的任务请求。
举个例子: Spring 通过 `ThreadPoolTaskExecutor` 或者我们直接通过 `ThreadPoolExecutor ` 的构造函数创建线程池的时候,当我们不指定 `RejectedExecutionHandler` 饱和策略的话来配置线程池的时候默认使用的是 `ThreadPoolExecutor.AbortPolicy`。在默认情况下,`ThreadPoolExecutor` 将抛出 `RejectedExecutionException` 来拒绝新来的任务 ,这代表你将丢失对这个任务的处理。 对于可伸缩的应用程序,建议使用 `ThreadPoolExecutor.CallerRunsPolicy`。当最大池被填满时,此策略为我们提供可伸缩队列。(这个直接查看 `ThreadPoolExecutor ` 的构造函数源码就可以看出,比较简单的原因,这里就不贴代码了。)
举个例子: Spring 通过 `ThreadPoolTaskExecutor` 或者我们直接通过 `ThreadPoolExecutor` 的构造函数创建线程池的时候,当我们不指定 `RejectedExecutionHandler` 饱和策略的话来配置线程池的时候默认使用的是 `ThreadPoolExecutor.AbortPolicy`。在默认情况下,`ThreadPoolExecutor` 将抛出 `RejectedExecutionException` 来拒绝新来的任务 ,这代表你将丢失对这个任务的处理。 对于可伸缩的应用程序,建议使用 `ThreadPoolExecutor.CallerRunsPolicy`。当最大池被填满时,此策略为我们提供可伸缩队列。(这个直接查看 `ThreadPoolExecutor` 的构造函数源码就可以看出,比较简单的原因,这里就不贴代码了。)
### 3.2 推荐使用ThreadPoolExecutor 构造函数创建线程池
### 3.2 推荐使用 `ThreadPoolExecutor` 构造函数创建线程池
**在《阿里巴巴 Java 开发手册》“并发处理”这一章节,明确指出线程资源必须通过线程池提供,不允许在应用中自行显示创建线程。**
@ -202,10 +138,10 @@ public class ScheduledThreadPoolExecutor
> Executors 返回线程池对象的弊端如下:
>
> - **FixedThreadPool 和 SingleThreadExecutor** 允许请求的队列长度为 Integer.MAX_VALUE,可能堆积大量的请求,从而导致 OOM。
> - **`FixedThreadPool``SingleThreadExecutor`** 允许请求的队列长度为 Integer.MAX_VALUE,可能堆积大量的请求,从而导致 OOM。
> - **CachedThreadPool 和 ScheduledThreadPool** 允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。
**方式一:通过`ThreadPoolExecutor `构造函数实现(推荐)**
**方式一:通过`ThreadPoolExecutor`构造函数实现(推荐)**
![通过构造方法实现](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzE3ODU4MjMwLmpwZw?x-oss-process=image/format,png)
**方式二:通过 Executor 框架的工具类 Executors 来实现**
我们可以创建三种类型的 ThreadPoolExecutor
@ -217,25 +153,30 @@ public class ScheduledThreadPoolExecutor
对应 Executors 工具类中的方法如图所示:
![通过Executor 框架的工具类Executors来实现](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzEzMjk2OTAxLmpwZw?x-oss-process=image/format,png)
## 四 ThreadPoolExecutor 使用示例
## 四 (重要)ThreadPoolExecutor 使用示例
我们上面讲解了 `Executor`框架以及 `ThreadPoolExecutor` 类,下面让我们实战一下,来通过写一个 `ThreadPoolExecutor` 的小 Demo 来回顾上面的内容。
### 4.1 示例代码
### 4.1 示例代码:`Runnable`+`ThreadPoolExecutor`
首先创建一个 `Runnable` 接口的实现类(当然也可以是 `Callable` 接口,我们上面也说了两者的区别是:`Runnable` 接口不会返回结果但是 `Callable` 接口可以返回结果。后面介绍 `Executors` 类的一些方法的时候会介绍到两者的相互转换。)
首先创建一个 `Runnable` 接口的实现类(当然也可以是 `Callable` 接口,我们上面也说了两者的区别。)
`MyRunnable.java`
```java
import java.util.Date;
/**
* 这是一个简单的Runnable类需要大约5秒钟来执行其任务。
* @author shuang.kou
*/
public class WorkerThread implements Runnable {
public class MyRunnable implements Runnable {
private String command;
public WorkerThread(String s) {
public MyRunnable(String s) {
this.command = s;
}
@ -259,21 +200,24 @@ public class WorkerThread implements Runnable {
return this.command;
}
}
```
编写测试程序,我们这里以阿里巴巴推荐的使用 `ThreadPoolExecutor` 构造函数自定义参数的方式来创建线程池。
`ThreadPoolExecutorDemo.java`
```java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorDemo {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) {
//使用阿里巴巴推荐的创建线程池的方式
@ -288,7 +232,7 @@ public class ThreadPoolExecutorDemo {
for (int i = 0; i < 10; i++) {
//创建WorkerThread对象WorkerThread类实现了Runnable 接口)
Runnable worker = new WorkerThread("" + i);
Runnable worker = new MyRunnable("" + i);
//执行Runnable
executor.execute(worker);
}
@ -299,12 +243,13 @@ public class ThreadPoolExecutorDemo {
System.out.println("Finished all threads");
}
}
```
可以看到我们上面的代码指定了:
1. `corePoolSize`: 核心线程数为 5。
2. `maximumPoolSize` :最大线程数 10
2. `maximumPoolSize` :最大线程数 10
3. `keepAliveTime` : 等待时间为 1L。
4. `unit`: 等待时间的单位为 TimeUnit.SECONDS。
5. `workQueue`:任务队列为 `ArrayBlockingQueue`,并且容量为 100;
@ -336,16 +281,16 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
```
### 4.2 原理分析
### 4.2 线程池原理分析
承接 5.1 节,我们通过代码输出结果可以看出:**线程池每次会同时执行 5 个任务这5 个任务执行完之后,剩余的 5 个任务才会被执行。** 大家可以先通过上面讲解的内容,分析一下到底是咋回事?(自己独立思考一会)
承接 5.1 节,我们通过代码输出结果可以看出:**线程池每次会同时执行 5 个任务,这 5 个任务执行完之后,剩余的 5 个任务才会被执行。** 大家可以先通过上面讲解的内容,分析一下到底是咋回事?(自己独立思考一会)
现在,我们就分析上面的输出内容来简单分析一下线程池原理。
**为了搞懂线程池的原理,我们需要首先分析一下 `execute`方法。**在 5.1 节中的 Demo 中我们使用 ` executor.execute(worker)`来提交一个任务到线程池中去,这个方法非常重要,下面我们来看看它的源码:
**为了搞懂线程池的原理,我们需要首先分析一下 `execute`方法。**在 5.1 节中的 Demo 中我们使用 `executor.execute(worker)`来提交一个任务到线程池中去,这个方法非常重要,下面我们来看看它的源码:
```java
// 存放线程池的运行状态 (runState) 和线程池内有效线程的数量 (workerCount)
// 存放线程池的运行状态 (runState) 和线程池内有效线程的数量 (workerCount)
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static int workerCountOf(int c) {
@ -362,7 +307,7 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
int c = ctl.get();
// 下面会涉及到 3 步 操作
// 1.首先判断当前线程池中之行的任务数量是否小于 corePoolSize
// 1.首先判断当前线程池中之行的任务数量是否小于 corePoolSize
// 如果小于的话通过addWorker(command, true)新建一个线程,并将任务(command)添加到该线程中;然后,启动该线程从而执行任务。
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
@ -370,7 +315,7 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
c = ctl.get();
}
// 2.如果当前之行的任务数量大于等于 corePoolSize 的时候就会走到这里
// 通过 isRunning 方法判断线程池状态,线程池处于 RUNNING 状态才会被并且队列可以加入任务,该任务才会被加入进去
// 通过 isRunning 方法判断线程池状态,线程池处于 RUNNING 状态才会被并且队列可以加入任务,该任务才会被加入进去
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// 再次获取线程池状态,如果线程池状态不是 RUNNING 状态就需要从任务队列中移除任务,并尝试判断线程是否全部执行完毕。同时执行拒绝策略。
@ -395,23 +340,162 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
没搞懂的话,也没关系,可以看看我的分析:
> 我们在代码中模拟了 10 个任务,我们配置的核心线程数为 5 、等待队列容量为 100 ,所以每次只可能存在 5 个任务同时执行,剩下的 5 个任务会被放到等待队列中去。当前的 5 个任务之行完成后,才会之行剩下的 5 个任务。
> 我们在代码中模拟了 10 个任务,我们配置的核心线程数为 5 、等待队列容量为 100 ,所以每次只可能存在 5 个任务同时执行,剩下的 5 个任务会被放到等待队列中去。当前的 5 个任务之行完成后,才会之行剩下的 5 个任务。
### 4.3 几个常见的方法对比
### 4.3 几个常见的对比
#### 4.3.1 shutdownVS shutdownNow
#### 4.3.1 `Runnable` vs `Callable`
- **`shutdown`** :关闭线程池,线程池的状态变为 `SHUTDOWN `。线程池不再接受新任务了,但是队列里的任务得执行完毕。
`Runnable`自 Java 1.0 以来一直存在,但`Callable`仅在 Java 1.5 中引入,目的就是为了来处理`Runnable`不支持的用例。**`Runnable` 接口**不会返回结果或抛出检查异常,但是**`Callable` 接口**可以。所以,如果任务不需要返回结果或抛出异常推荐使用 **`Runnable` 接口**,这样代码看起来会更加简洁。
工具类 `Executors` 可以实现 `Runnable` 对象和 `Callable` 对象之间的相互转换。(`Executors.callableRunnable task`)或 `Executors.callableRunnable taskObject resule`)。
`Runnable.java`
```java
@FunctionalInterface
public interface Runnable {
/**
* 被线程执行,没有返回值也无法抛出异常
*/
public abstract void run();
}
```
`Callable.java`
```java
@FunctionalInterface
public interface Callable<V> {
/**
* 计算结果,或在无法这样做时抛出异常。
* @return 计算得出的结果
* @throws 如果无法计算结果,则抛出异常
*/
V call() throws Exception;
}
```
#### 4.3.2 `execute()` vs `submit()`
1. **`execute()`方法用于提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功与否;**
2. **`submit()`方法用于提交需要返回值的任务。线程池会返回一个 `Future` 类型的对象,通过这个 `Future` 对象可以判断任务是否执行成功**,并且可以通过 `Future``get()`方法来获取返回值,`get()`方法会阻塞当前线程直到任务完成,而使用 `getlong timeoutTimeUnit unit`方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完。
我们以**`AbstractExecutorService`**接口中的一个 `submit` 方法为例子来看看源代码:
```java
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
```
上面方法调用的 `newTaskFor` 方法返回了一个 `FutureTask` 对象。
```java
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
```
我们再来看看`execute()`方法:
```java
public void execute(Runnable command) {
...
}
```
#### 4.3.3 `shutdown()`VS`shutdownNow()`
- **`shutdown`** :关闭线程池,线程池的状态变为 `SHUTDOWN`。线程池不再接受新任务了,但是队列里的任务得执行完毕。
- **`shutdownNow`** :关闭线程池,线程的状态变为 `STOP`。线程池会终止当前正在运行的任务,并停止处理排队的任务并返回正在等待执行的 List。
#### 4.3.2 isTerminated() Vs isShutdown()
#### 4.3.2 `isTerminated()` VS `isShutdown()`
- **`isShutDown`** 当调用 `shutdown()` 方法后返回为true。
- **`isTerminated`** 当调用 `shutdown()` 方法后并且所有提交的任务完成后返回为true
- **`isShutDown`** 当调用 `shutdown()` 方法后返回为 true。
- **`isTerminated`** 当调用 `shutdown()` 方法后,并且所有提交的任务完成后返回为 true
##五 几种常见的线程池详解
### 4.4 加餐:`Callable`+`ThreadPoolExecutor`示例代码
### 5.1 FixedThreadPool 详解
`MyCallable.java`
```java
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
//返回执行当前 Callable 的线程名字
return Thread.currentThread().getName();
}
}
```
`CallableDemo.java`
```java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CallableDemo {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) {
//使用阿里巴巴推荐的创建线程池的方式
//通过ThreadPoolExecutor构造函数自定义参数创建
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
List<Future<String>> futureList = new ArrayList<>();
Callable<String> callable = new MyCallable();
for (int i = 0; i < 10; i++) {
//提交任务到线程池
Future<String> future = executor.submit(callable);
//将返回值 future 添加到 list我们可以通过 future 获得 执行 Callable 得到的返回值
futureList.add(future);
}
for (Future<String> fut : futureList) {
try {
System.out.println(new Date() + "::" + fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
//关闭线程池
executor.shutdown();
}
}
```
##五 几种常见的线程池详解
### 5.1 FixedThreadPool
#### 5.1.1 介绍
`FixedThreadPool` 被称为可重用固定线程数的线程池。通过 Executors 类中的相关源代码来看一下相关实现:
@ -437,8 +521,11 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
}
```
从上面源代码可以看出新创建的 FixedThreadPool 的 corePoolSize 和 maximumPoolSize 都被设置为 nThreads。
**FixedThreadPool 的 execute()方法运行示意图该图片来源《Java 并发编程的艺术》):**
**从上面源代码可以看出新创建的 `FixedThreadPool``corePoolSize``maximumPoolSize` 都被设置为 nThreads这个 nThreads 参数是我们使用的时候自己传递的。**
#### 5.1.2 执行任务过程介绍
`FixedThreadPool``execute()` 方法运行示意图该图片来源《Java 并发编程的艺术》):
![FixedThreadPool的execute()方法运行示意图](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzcxMzc1OTYzLmpwZw?x-oss-process=image/format,png)
@ -448,26 +535,24 @@ pool-1-thread-1 End. Time = Tue Nov 12 20:59:54 CST 2019
2. 当前运行的线程数等于 corePoolSize 后, 如果再来新任务的话,会将任务加入 `LinkedBlockingQueue`
3. 线程池中的线程执行完 手头的任务后,会在循环中反复从 `LinkedBlockingQueue` 中获取任务来执行;
**FixedThreadPool 使用无界队列 LinkedBlockingQueue队列的容量为 Intger.MAX_VALUE作为线程池的工作队列会对线程池带来如下影响**
#### 5.1.3 为什么不推荐使用`FixedThreadPool`
1. 当线程池中的线程数达到 corePoolSize 后,新任务将在无界队列中等待,因此线程池中的线程数不会超过 corePoolSize
2. 由于 1使用无界队列时 maximumPoolSize 将是一个无效参数;
3. 由于 1 和 2使用无界队列时 keepAliveTime 将是一个无效参数;
4. 运行中的 FixedThreadPool未执行 shutdown()或 shutdownNow()方法)不会拒绝任务
**`FixedThreadPool` 使用无界队列 `LinkedBlockingQueue`(队列的容量为 Intger.MAX_VALUE作为线程池的工作队列会对线程池带来如下影响 **
1. 当线程池中的线程数达到 `corePoolSize` 后,新任务将在无界队列中等待,因此线程池中的线程数不会超过 corePoolSize
2. 由于使用无界队列时 `maximumPoolSize` 将是一个无效参数,因为不可能存在任务队列满的情况。所以,通过创建 `FixedThreadPool`的源码可以看出创建的 `FixedThreadPool``corePoolSize``maximumPoolSize` 被设置为同一个值。
3. 由于 1 和 2使用无界队列时 `keepAliveTime` 将是一个无效参数;
4. 运行中的 `FixedThreadPool`(未执行 `shutdown()``shutdownNow()`)不会拒绝任务,在任务比较多的时候会导致 OOM内存溢出
### 5.2 SingleThreadExecutor 详解
SingleThreadExecutor 是使用单个 worker 线程的 Executor。下面看看**SingleThreadExecutor 的实现:**
#### 5.2.1 介绍
`SingleThreadExecutor` 是只有一个线程的线程池。下面看看**SingleThreadExecutor 的实现:**
```java
/**
*创建使用单个worker线程运行无界队列的Executor
*并使用提供的ThreadFactory在需要时创建新线程
*
* @param threadFactory 创建新线程时使用的factory
*
* @return 新创建的单线程Executor
* @throws NullPointerException 如果ThreadFactory为空
*返回只有一个线程的线程池
*/
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
@ -487,28 +572,32 @@ SingleThreadExecutor 是使用单个 worker 线程的 Executor。下面看看**S
}
```
从上面源代码可以看出新创建的 SingleThreadExecutor 的 corePoolSize 和 maximumPoolSize 都被设置为 1.其他参数和 FixedThreadPool 相同。SingleThreadExecutor 使用无界队列 LinkedBlockingQueue 作为线程池的工作队列(队列的容量为 Intger.MAX_VALUE。SingleThreadExecutor 使用无界队列作为线程池的工作队列会对线程池带来的影响与 FixedThreadPool 相同。
从上面源代码可以看出新创建的 `SingleThreadExecutor``corePoolSize``maximumPoolSize` 都被设置为 1.其他参数和 `FixedThreadPool` 相同。
**SingleThreadExecutor 的运行示意图该图片来源《Java 并发编程的艺术》):**
#### 5.2.2 执行任务过程介绍
**`SingleThreadExecutor` 的运行示意图该图片来源《Java 并发编程的艺术》):**
![SingleThreadExecutor的运行示意图](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzgyMjc2NDU4LmpwZw?x-oss-process=image/format,png)
**上图说明;**
1. 如果当前运行的线程数少于 corePoolSize则创建一个新的线程执行任务
2. 当前线程池中有一个运行的线程后,将任务加入 LinkedBlockingQueue
3. 线程执行完 1 中的任务后,会在循环中反复从 LinkedBlockingQueue 中获取任务来执行;
2. 当前线程池中有一个运行的线程后,将任务加入 `LinkedBlockingQueue`
3. 线程执行完当前的任务后,会在循环中反复从` LinkedBlockingQueue` 中获取任务来执行;
#### 5.2.3 为什么不推荐使用`FixedThreadPool`
`SingleThreadExecutor` 使用无界队列 `LinkedBlockingQueue` 作为线程池的工作队列(队列的容量为 Intger.MAX_VALUE`SingleThreadExecuto`r 使用无界队列作为线程池的工作队列会对线程池带来的影响与 `FixedThreadPool` 相同。说简单点就是可能会导致 OOM
### 5.3 CachedThreadPool 详解
CachedThreadPool 是一个会根据需要创建新线程的线程池。下面通过源码来看看 CachedThreadPool 的实现:
#### 5.3.1 介绍
`CachedThreadPool` 是一个会根据需要创建新线程的线程池。下面通过源码来看看 `CachedThreadPool` 的实现:
```java
/**
* 创建一个线程池,根据需要创建新线程,但会在先前构建的线程可用时重用它,
*并在需要时使用提供的ThreadFactory创建新线程。
* @param threadFactory 创建新线程使用的factory
* @return 新创建的线程池
* @throws NullPointerException 如果threadFactory为空
* 创建一个线程池,根据需要创建新线程,但会在先前构建的线程可用时重用它。
*/
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
@ -527,15 +616,21 @@ CachedThreadPool 是一个会根据需要创建新线程的线程池。下面通
}
```
CachedThreadPool 的 corePoolSize 被设置为空0maximumPoolSize 被设置为 Integer.MAX.VALUE即它是无界的这也就意味着如果主线程提交任务的速度高于 maximumPool 中线程处理任务的速度时CachedThreadPool 会不断创建新的线程。极端情况下,这样会导致耗尽 cpu 和内存资源。
`CachedThreadPool`` corePoolSize` 被设置为空0`maximumPoolSize `被设置为 Integer.MAX.VALUE即它是无界的这也就意味着如果主线程提交任务的速度高于 `maximumPool` 中线程处理任务的速度时,`CachedThreadPool` 会不断创建新的线程。极端情况下,这样会导致耗尽 cpu 和内存资源。
#### 5.3.2 执行任务过程介绍
**CachedThreadPool 的 execute()方法的执行示意图该图片来源《Java 并发编程的艺术》):**
![CachedThreadPool的execute()方法的执行示意图](https://imgconvert.csdnimg.cn/aHR0cDovL215LWJsb2ctdG8tdXNlLm9zcy1jbi1iZWlqaW5nLmFsaXl1bmNzLmNvbS8xOC00LTE2LzE4NjExNzY3LmpwZw?x-oss-process=image/format,png)
**上图说明:**
1. 首先执行 SynchronousQueue.offer(Runnable task)。如果当前 maximumPool 中有闲线程正在执行 SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS),那么主线程执行 offer 操作与空闲线程执行的 poll 操作配对成功主线程把任务交给空闲线程执行execute()方法执行完成,否则执行下面的步骤 2
2. 当初始 maximumPool 为空,或者 maximumPool 中没有空闲线程时,将没有线程执行 SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)。这种情况下,步骤 1 将失败,此时 CachedThreadPool 会创建新线程执行任务execute 方法执行完成;
1. 首先执行 `SynchronousQueue.offer(Runnable task)` 提交任务到任务队列。如果当前 `maximumPool` 中有闲线程正在执行 `SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)`,那么主线程执行 offer 操作与空闲线程执行的 `poll` 操作配对成功,主线程把任务交给空闲线程执行,`execute()`方法执行完成,否则执行下面的步骤 2
2. 当初始 `maximumPool` 为空,或者 `maximumPool` 中没有空闲线程时,将没有线程执行 `SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)`。这种情况下,步骤 1 将失败,此时 `CachedThreadPool` 会创建新线程执行任务execute 方法执行完成;
#### 5.3.3 为什么不推荐使用`CachedThreadPool`
`CachedThreadPool`允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。
## 六 ScheduledThreadPoolExecutor 详解
@ -547,9 +642,9 @@ CachedThreadPool 的 corePoolSize 被设置为空0maximumPoolSize 被
**`ScheduledThreadPoolExecutor``Timer` 的比较:**
- `Timer` 对系统时钟的变化敏感,`ScheduledThreadPoolExecutor `不是;
- `Timer` 对系统时钟的变化敏感,`ScheduledThreadPoolExecutor`不是;
- `Timer` 只有一个执行线程,因此长时间运行的任务可以延迟其他任务。 `ScheduledThreadPoolExecutor` 可以配置任意数量的线程。 此外,如果你想(通过提供 ThreadFactory你可以完全控制创建的线程;
- 在` TimerTask` 中抛出的运行时异常会杀死一个线程,从而导致 `Timer` 死机:-( ...即计划任务将不再运行。`ScheduledThreadExecutor` 不仅捕获运行时异常,还允许您在需要时处理它们(通过重写 `afterExecute` 方法` ThreadPoolExecutor`)。抛出异常的任务将被取消,但其他任务将继续运行。
- 在`TimerTask` 中抛出的运行时异常会杀死一个线程,从而导致 `Timer` 死机:-( ...即计划任务将不再运行。`ScheduledThreadExecutor` 不仅捕获运行时异常,还允许您在需要时处理它们(通过重写 `afterExecute` 方法`ThreadPoolExecutor`)。抛出异常的任务将被取消,但其他任务将继续运行。
**综上,在 JDK1.5 之后,你没有理由再使用 Timer 进行任务调度了。**
@ -771,5 +866,5 @@ scheduleWithFixedDelay...)将延迟视为一个任务结束与下一个任
## 十 其他推荐阅读
- [Java并发(三)线程池原理](https://www.cnblogs.com/warehouse/p/10720781.html)
- [如何优雅的使用和理解线程池](https://github.com/crossoverJie/JCSprout/blob/master/MD/ThreadPoolExecutor.md)
- [Java 并发(三)线程池原理](https://www.cnblogs.com/warehouse/p/10720781.html "Java并发线程池原理")
- [如何优雅的使用和理解线程池](https://github.com/crossoverJie/JCSprout/blob/master/MD/ThreadPoolExecutor.md "如何优雅的使用和理解线程池")