8. 执行线程
本章介绍在单个程序中同时执行多段代码:线程 (执行线程)以及用于同步它们的工具。大约二十年前,大多数机器只有一个处理器,并行在很大程度上是由操作系统营造的一种假象。如今,即使是最基本的笔记本电脑也有多个核心:多个线程确实在同时运行,这使得这里讨论的同步问题更加普遍。
Java 从第一个版本(1996 年)起就支持线程:[Thread] 类、[synchronized] 关键字,以及 [wait] / [notify] 方法(属于 [Object] 类)。Java 5(2004 年)增加了 [java.util.concurrent] 包及其子包 [java.util.concurrent.locks] 和 [java.util.concurrent.atomic]:锁、信号量、并发集合、线程池等。Java 7 增加了 [Fork/Join] 框架,Java 8 引入了并行流,Java 21 引入了 虚拟线程,所有这些都深刻改变了服务器的编写方式。Java 25 终于引入了作用域值([ScopedValue])。我们将在本章探讨所有这些工具。
这些示例是紧凑源文件([java Threads01.java]),位于 [08-threads] 文件夹中。请记住,紧凑源文件会自动导入整个 [java.base] 模块:因此,包 [java.util.concurrent]、[java.util.concurrent.locks]、[java.util.concurrent.atomic] 和 [java.time] 中的类无需 [import] 指令即可使用。
开始之前先提醒一句:多线程程序的结果每次运行都不尽相同。线程被分配处理器的顺序取决于操作系统、处理器数量和机器的负载。本章所示的结果是在一台与其他高度活跃的程序共享的双处理器 Linux 机器上得到的。如果您运行这些示例,会得到相似的结果,但很少会完全相同。我们会在每种情况下指出哪些是可重现的,哪些不是。
8.1. Thread 类
应用程序启动时,它运行在一个称为线程的执行流中。表示线程的 Java 类是 [java.lang.Thread] 类。它的主要构造函数和方法如下:
成员 | 作用 |
[Thread(Runnable task)]、[Thread(Runnable task, String name)] | 创建一个线程,它将执行 [run] 方法,该方法属于 [task]。[Runnable] 是 [void run()] 的函数式接口:传给它的通常是 lambda 或方法引用 |
[static Thread.Builder.OfPlatform ofPlatform()], [static Thread.Builder.OfVirtual ofVirtual()] | (Java 21)返回用于平台线程或 虚拟线程的构建器,在创建线程之前可以先对其进行配置(名称、守护线程等) |
[static Thread currentThread()] | 执行调用此方法的代码的线程 |
[String getName()]、[void setName(String name)] | 线程的名称,便于跟踪 |
[long threadId()] | (Java 19)线程的唯一数字标识符;它取代 [getId()](已弃用) |
[boolean isDaemon()]、[void setDaemon(boolean b)] | 指示线程是否为守护线程(固定不变)(见下文) |
[int getPriority()]、[void setPriority(int p)] | 线程的优先级,从 1([MIN_PRIORITY])到 10([MAX_PRIORITY]),默认为 5([NORM_PRIORITY]) |
[Thread.State getState()]、[boolean isAlive()] | 线程状态([NEW]、[RUNNABLE]、[BLOCKED]、[WAITING]、[TIMED_WAITING]、[TERMINATED]);[isAlive] 表示线程是否已启动但尚未结束 |
[boolean isVirtual()] | (Java 21)指示线程是否为虚拟线程 |
[void start()] | 启动线程的执行 |
[void join()]、[boolean join(Duration timeout)] | 执行 [T2.join()], 的线程 T1 会被阻塞,直到线程 T2 结束。第二种形式(Java 19)限制等待时间,并指示 T2 是否已结束 |
[static void sleep(long ms)]、[static void sleep(Duration d)] | 执行该方法的线程被挂起 [ms] 毫秒(挂起时长为 [d])。它让出 CPU,CPU 被交给另一个线程 |
[void interrupt()]、[boolean isInterrupted()] | 请求线程暂停;检查是否已请求暂停(见下文) |
如果线程在等待时被中断,方法 [join] 和 [sleep] 会抛出受检异常 [InterruptedException] :编译器要求处理或声明它。我们将在中断一节中讨论它的含义。
[Thread] 类还有一个方法 [stop], 它过去用于强行终止线程。它自 Java 1.2 起就已弃用,自 Java 20 起,它只是抛出 [UnsupportedOperationException] 异常:突然停止线程可能会使它正在处理的数据处于不一致的状态。如今,我们请求线程 协作式地 停止,方法是 中断它:稍后我们会讨论这一点。
下面是第一个应用程序,它演示了主执行线程的存在——即执行 [main] 方法的线程。[Threads01.java] 程序如下:
| // 程序的主线程
void main() throws InterruptedException {
// 执行此代码的线程
Thread main = Thread.currentThread();
// Java 启动器给它起了名字
IO.println("Name of the current thread: [" + main.getName() + "]");
// 我们可以修改它
main.setName("Main");
IO.println("Name of the current thread: [" + main.getName() + "]");
// 一些属性
IO.println("Identifier (threadId): " + main.threadId());
IO.println("Daemon thread (isDaemon): " + main.isDaemon());
IO.println("Virtual thread (isVirtual): " + main.isVirtual());
IO.println("Priority (getPriority): " + main.getPriority());
IO.println("State (getState): " + main.getState());
IO.println("Text representation: " + main);
IO.println("Number of processors: " + Runtime.getRuntime().availableProcessors());
// 每秒显示一次
var format = DateTimeFormatter.ofPattern("HH:mm:ss");
for (int i = 0; i < 5; i++) {
IO.println(main.getName() + " : " + LocalTime.now().format(format));
// 线程挂起 1 秒
Thread.sleep(1000);
}
}
|
结果:
| > java Threads01.java
Name of the current thread: [main]
Name of the current thread: [Main]
Identifier (threadId): 3
Daemon thread (isDaemon): false
Virtual thread (isVirtual): false
Priority (getPriority): 5
State (getState): RUNNABLE
Text representation: Thread[#3,Main,5,main]
Number of processors: 2
Main : 19:14:06
Main : 19:14:07
Main : 19:14:08
Main : 19:14:09
Main : 19:14:10
|
说明:
- 第 5 行:获取对执行该程序的线程的引用;
- 第 7–10 行:我们显示它的名称,修改它,然后再次显示。最初,主线程名为 [main] (结果的第 2 行):这是 Java 启动器赋予它的名称;
- 第 12–18 行:线程的一些属性。在这次执行中,主线程的 ID 为 3:虚拟机在执行 [main] 之前会为自身的目的创建一些线程,而且这个 ID 可能因 Java 版本而异。它既不是 守护 线程([isDaemon()] 等于 [false]),也不是 虚拟 线程(我们稍后会讨论这两个概念);它的优先级是正常优先级 5;它当前正在运行([RUNNABLE])。线程的 [toString] 方法(第 17 行)显示它的 ID、名称、优先级以及所属线程组的名称([main]);
- 第 18 行:运行该示例的机器有 2 个处理器;
- 第 21–26 行:一个每秒显示一次输出的循环。[Thread.sleep(1000)] 把主线程挂起一秒钟。由于 [sleep] 可能抛出受检异常 [InterruptedException],方法 [main] 在它的 [throws] 子句中声明了它(第 3 行)。请注意 [HH:mm:ss] 格式(小时为 0 到 23):[hh] 格式则会显示 1 到 12 的小时。
8.2. 创建执行线程
可以让应用程序中的各段代码在不同的执行线程中“同时”执行。如果机器的处理器数量少于准备执行的线程数,这些线程就会共享处理器:每个线程轮流使用处理器很短的一段时间(几毫秒)。在多处理器机器上,多个线程确实在同时执行。分配给线程的时间取决于多种因素,包括它的优先级,优先级有默认值,但可以通过编程方式设置([setPriority]);这只是一种参考,操作系统可以自由忽略它(Linux 默认会忽略它)。获得处理器的线程可以提前释放它:
- 通过等待某个事件(使用 [join] 等待另一个线程结束,或等待信号);
- 通过休眠指定的一段时间([sleep])。
线程 T 首先被创建,例如通过构造函数 [new Thread(task, name)],其中 [task] 是实现函数式接口 [Runnable] 的对象,该接口唯一的方法是 [void run()]。这个对象通常是 lambda 或方法引用(函数式接口已在第 7 章介绍)。在较旧的代码中,您还可能遇到派生自 *[Thread]* 并重新定义其方法 *[run]* 的类:不推荐这样做,因为它把要执行的任务与执行任务的手段混在了一起。
创建线程并不会启动它:
- 线程 T 的执行由 [T.start()] 启动:传给 T 的构造函数的任务的 [run] 方法随后将由线程 T 执行。执行 [T.start()] 指令的代码不会等待线程 T 结束:它立即转到下一条指令。现在我们有两个线程在并行运行。它们常常需要彼此通信,以跟踪共同工作的进展:这就是线程 同步的问题;
- 线程 T 一旦启动,就自主运行。当它正在执行的方法结束时,它就停止;
- 我们可以使用 [T.join()] 等待它执行完毕。这是一条阻塞指令:执行它的线程会被阻塞,直到线程 T 完成它的工作。这是一种基本的同步方法。
程序 [Threads02.java] 如下:
| // 创建执行线程
void main() {
// 我们为主线程命名
Thread.currentThread().setName("Main");
// 创建 5 个线程
var tasks = new Thread[5];
for (int i = 0; i < tasks.length; i++) {
// 第 i 号线程将执行 display 方法,我们给它命名为 "i"
tasks[i] = new Thread(this::display, String.valueOf(i));
// 我们启动其执行(非阻塞操作)
tasks[i].start();
}
// 主线程结束
IO.println("End of thread " + Thread.currentThread().getName() + " at " + time());
}
// 线程执行的方法:它具有 Runnable.run() 的签名
void display() {
// 执行该方法的线程
Thread current = Thread.currentThread();
IO.println("Start of execution of the display method in thread " + current.getName()
+ " (id " + current.threadId() + ") : " + time());
// 休眠 1 秒
sleep(1000);
IO.println("End of execution of the display method in thread " + current.getName()
+ " : " + time());
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// 休眠被中断:我们恢复线程的中断标志
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5 行:我们给主线程起一个名字;
- 第 8–14 行:创建并启动 5 个线程。它们的引用存储在一个数组中,以便以后取用。每个线程执行第 21–30 行的 [display] 方法;
- 第 11 行:方法引用 [this::display] 会被自动转换为 [Runnable] 对象:方法 [display] 与 [run] 一样,没有参数也没有返回结果。我们写成 [this::display] 是因为在紧凑源文件中,声明在任何类之外的方法是隐式类的实例方法,而这个类的名称不能在代码中使用。构造函数的第二个参数是线程名称;
- 第 13 行:启动线程 #i。该操作是非阻塞的:线程 #i 与启动它的主线程并行运行;
- 第 17 行:主线程到达程序末尾;
- 第 21–30 行:[display] 方法显示执行它的线程的名称和 ID,以及执行的开始和结束时间(精确到毫秒);
- 第 27 行:任何执行 [display] 方法的线程都会暂停 1 秒。处理器随后被交给另一个等待处理器的线程。1 秒的暂停结束时,暂停的线程重新有资格获得处理器。轮到它时,它就会获得处理器;
- 第 33–40 行:方法 [sleep] 封装了 [Thread.sleep]。[Runnable] 中的方法 [run] 不声明任何受检异常:因此,[display] 方法不能让 [InterruptedException] 异常(由 [sleep] 抛出)逃逸出去。方法 [sleep] 会拦截它并重置线程的中断标志(第 38 行);我们将在中断一节中解释这个操作。在本章的大多数程序中,我们都会遇到这个小方法;
- 第 43–45 行:方法 [time] 以 [HH:mm:ss.SSS] 格式([SSS]:毫秒)返回当前时间。
结果:
| > java Threads02.java
Start of execution of the display method in thread 4 (id 26) : 19:14:13.727
Start of execution of the display method in thread 1 (id 23) : 19:14:13.728
Start of execution of the display method in thread 0 (id 22) : 19:14:13.729
Start of execution of the display method in thread 2 (id 24) : 19:14:13.732
End of thread Main at 19:14:13.725
Start of execution of the display method in thread 3 (id 25) : 19:14:13.732
End of execution of the display method in thread 2 : 19:14:14.744
End of execution of the display method in thread 3 : 19:14:14.746
End of execution of the display method in thread 1 : 19:14:14.746
End of execution of the display method in thread 4 : 19:14:14.747
End of execution of the display method in thread 0 : 19:14:14.747
|
这些结果提供了很多信息:
- 首先,我们可以看到启动线程是非阻塞的。主线程启动了 5 个线程,并在线程 3 尚未显示它的第一条消息时就到达了程序末尾(第 6 行);
- 线程的执行顺序是不可预测的:在这次运行中,线程 4 比线程 0 先显示它的开始消息。这里操作系统有 6 个线程和 2 个处理器;它按照自己的规则把处理器分配给这些线程;
- 我们还注意到,显示的顺序并不总是遵循所显示时间的顺序:主线程在 13.725 显示了它的结束,而此前已有时间标记为 13.727 到 13.732 的消息。时间是在输出 之前 计算的,在此期间,另一个线程可能已经向控制台写了内容。[IO.println] (与 [System.out.println] 一样)是线程安全的:两个线程写入的两行不会混在一起,但它们的顺序没有保证;
- 所创建线程的 ID(22 到 26)表明,虚拟机已经为自身的目的创建了大约二十个线程(垃圾回收、即时编译器等);
- 每个线程在 [sleep] 处暂停一秒钟,然后完成 [display] 方法的执行;
- 最后,程序并没有在主线程完成工作时停止:虚拟机等待所有五个线程完成。这是因为这些线程不是 守护 线程:当所有非守护线程都结束时,Java 虚拟机才会停止。
反过来,线程可以 被声明 为守护线程,方法是在启动前调用 [setDaemon(true)] 。守护线程是不妨碍虚拟机停止的服务线程:当最后一个非守护线程终止时,它们就会被停止。程序 [Threads03.java] 如下:
| // 守护线程
void main() {
// 我们为主线程命名
Thread.currentThread().setName("Main");
// 线程构建器:平台线程、守护线程,命名为 0、1、2……
Thread.Builder builder = Thread.ofPlatform().daemon().name("", 0);
// 创建并启动 5 个守护线程
for (int i = 0; i < 5; i++) {
// start 创建线程并立即启动它
builder.start(this::display);
}
// 我们给线程留出启动的时间
sleep(100);
// 主线程结束,因此程序也结束
IO.println("End of thread " + Thread.currentThread().getName() + " at " + time());
}
// 线程执行的方法
void display() {
Thread current = Thread.currentThread();
IO.println("Start of execution of the display method in thread " + current.getName()
+ " : " + time());
// 休眠 1 秒
sleep(1000);
IO.println("End of execution of the display method in thread " + current.getName()
+ " : " + time());
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 8 行:从 Java 21 开始,[Thread.ofPlatform()] 方法返回一个 线程构建器 ,类型为 [Thread.Builder],通过链式调用对其进行配置:[daemon()] 请求创建守护线程;[name("", 0)] 指定线程以一个前缀(这里是空字符串)后接一个数字来命名,该数字从 0 开始,每创建一个线程就加一。平台线程是我们从本章开头一直在使用的“经典”线程,与稍后讨论的虚拟线程相对;
- 第 12 行:构建器的方法 [start(Runnable)] 创建一个线程并立即启动它。它的方法 [unstarted(Runnable)] 创建线程但不启动它;
- 第 16 行:主线程等待 100 毫秒,让各线程有时间启动,然后终止。
结果:
| > java Threads03.java
Start of execution of the display method in thread 1 : 19:14:17.388
Start of execution of the display method in thread 0 : 19:14:17.424
End of thread Main at 19:14:17.425
Start of execution of the display method in thread 3 : 19:14:17.366
|
五个线程中有三个开始了执行,然后主线程终止了(第 4 行)。线程 3 在主线程结束之前已经计算好了它的消息的时间,但直到之后(第 5 行),也就是虚拟机正在关闭时,才得以显示它。守护线程随后在它们一秒钟的休眠期间被终止:没有显示任何结束消息。有两个线程甚至来不及显示它们的开始消息:由于机器负载很重,100 毫秒不足以让它们获得 CPU(再运行一次会得到不同数量的开始消息,但绝不会有结束消息)。通过用 [main] 终止 [System.exit(0)] 也能达到同样的效果,它会关闭虚拟机——从而关闭应用程序的所有线程,无论是否为守护线程。我们稍后将讨论的虚拟线程始终是守护线程。
如果主线程想等待它所创建的线程结束,就使用 [join] 方法。[Threads04.java] 程序还演示了指定线程要执行的代码的另一种方式:lambda。
| // 用 join 等待线程结束:用 lambda 表达式创建的线程
void main() throws InterruptedException {
// 我们为主线程命名
Thread.currentThread().setName("Main");
// 创建 5 个线程
var tasks = new Thread[5];
for (int i = 0; i < tasks.length; i++) {
// i 的局部副本:lambda 表达式只能使用实际上为 final 的变量
int number = i;
// 线程执行 lambda 表达式,后者以类型化参数调用 display
tasks[i] = new Thread(() -> display(number, 1000 + 100 * number), String.valueOf(i));
tasks[i].start();
}
// 我们等待所有线程结束
for (Thread task : tasks) {
// 主线程被阻塞,直到线程 [task] 结束
task.join();
}
// 主线程结束
IO.println("End of thread " + Thread.currentThread().getName() + " at " + time());
}
// 线程执行的方法
static void display(int number, long duration) {
String name = Thread.currentThread().getName();
IO.println("Start of execution of task " + number + " in thread " + name + " : " + time());
// 休眠 [duration] 毫秒
sleep(duration);
IO.println("End of execution of task " + number + " in thread " + name + " : " + time());
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 13 行:线程执行 lambda [() -> display(number, 1000 + 100 * number)]。没有参数也没有返回值的 lambda 与 [Runnable] 接口兼容。这种语法允许调用带有类型化参数的方法(这里是一个 [int] 和一个 [long]),而 [run] 没有参数;
- 第 11 行:lambda 使用循环变量 [i] 的一个副本。这是强制性的:lambda 只能使用 实际上是 final 的局部变量,也就是说,这些变量在初始化之后从不被修改。变量 [i] 被循环修改([i++]):如果 lambda 使用它,编译器就会拒绝该程序(“local variables referenced from a lambda expression must be final or effectively final”)。而在循环体内声明的变量 [number] 则是每次迭代都有的新变量,并且从不被修改。这条规则可以防范一个常见的陷阱:如果没有它,较晚启动的线程可能会读到后续迭代中 [i] 的值,甚至读到最终值 5;
- 第 18–21 行:主线程等待每一个线程。它先因等待线程 0 而被阻塞,然后是线程 1,依此类推。当它退出循环时,它所启动的 5 个线程都已结束。由于 [join] 可能抛出 [InterruptedException],[main] 会抛出这个异常(第 3 行);
- 第 31 行:任务 #i 休眠 1,000 + 100 × i 毫秒,这样线程就按已知的顺序终止。
结果:
| > java Threads04.java
Start of execution of task 1 in thread 1 : 19:14:21.035
Start of execution of task 2 in thread 2 : 19:14:21.035
Start of execution of task 3 in thread 3 : 19:14:21.035
Start of execution of task 4 in thread 4 : 19:14:21.032
Start of execution of task 0 in thread 0 : 19:14:21.035
End of execution of task 0 in thread 0 : 19:14:22.039
End of execution of task 1 in thread 1 : 19:14:22.140
End of execution of task 2 in thread 2 : 19:14:22.239
End of execution of task 3 in thread 3 : 19:14:22.360
End of execution of task 4 in thread 4 : 19:14:22.440
End of thread Main at 19:14:22.440
|
开始消息以任意顺序出现,但结束消息按数字顺序出现,因为休眠时长是递增的:结果的这一部分是可重现的。最后一行显示,主线程在它所启动的线程之后终止,即在最后一个线程终止的那一刻。
8.3. 停止线程:中断
如何在线程完成工作之前停止它,例如当用户取消一个长时间运行的操作时?Java 不允许您杀死线程;相反,它提供了一种称为 中断的协作机制:
- 每个线程都有一个 中断标志,这是一个布尔值,初始为 [false];
- 想要停止线程 T2 的线程 T1 调用 [T2.interrupt()]。这会设置 T2 的中断标志。这是一个终止 请求 :T2 并未被终止;由该线程自己决定何时以及如何终止自己,以便让它的数据保持一致的状态;
- 如果 T2 阻塞在某个等待方法中([sleep]、[join]、[wait],以及 [java.util.concurrent] 中的大多数阻塞方法),它就会被唤醒:该方法抛出 [InterruptedException] 异常,并且中断标志被重置为 [false];
- 如果 T2 执行的计算从不等待,它就必须定期使用 [Thread.currentThread().isInterrupted()] 检查自己的标志。
这就是为什么阻塞方法要声明受检异常 [InterruptedException]:编译器要求程序员决定如何处理停止请求。有两种正确的响应:让异常传播给调用者(在 [throws] 子句中声明它),或者捕获它并干净利落地结束任务。当这两种做法都不可行时,比如上一个程序的 [sleep] 方法,就使用 [Thread.currentThread().interrupt()] 重新设置标志,这样调用方代码仍然能看到这个请求。唯一不正确的响应是忽略该异常。程序 [Threads05.java] 演示了这三种情况:
| // 停止线程:中断
void main() throws InterruptedException {
// 1 - 大部分时间处于休眠的线程
Thread sleeper = Thread.ofPlatform().name("sleeper").start(() -> {
int round = 0;
try {
while (true) {
round++;
IO.println(time() + " : sleeper, round " + round);
// 如果线程在休眠时被中断,sleep 会抛出 InterruptedException
Thread.sleep(400);
}
} catch (InterruptedException e) {
// 中断是一个停止请求:线程干净地完成其工作
IO.println(time() + " : sleeper interrupted while sleeping, it stops");
}
});
// 2 - 从不休眠、持续计算的线程
Thread calculator = Thread.ofPlatform().name("calculator").start(() -> {
long n = 0;
// 线程定期检查其中断标志
while (!Thread.currentThread().isInterrupted()) {
n++;
}
IO.println(time() + " : calculator interrupted after %,d iterations, it stops".formatted(n));
});
// 3 - 忽略中断的线程(不要模仿)
Thread deaf = Thread.ofPlatform().name("deaf").daemon().start(() -> {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// 异常被“吞掉”了:停止请求丢失
IO.println(time() + " : deaf ignores the interruption and continues");
}
}
});
// 我们让线程工作 1 秒
Thread.sleep(1000);
IO.println(time() + " : Main requests the three threads to stop");
sleeper.interrupt();
calculator.interrupt();
deaf.interrupt();
// 等待每个线程结束,最多等待 1 秒
for (Thread thread : List.of(sleeper, calculator, deaf)) {
boolean finished = thread.join(Duration.ofSeconds(1));
IO.println(time() + " : thread " + thread.getName() + " finished: " + finished);
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5–18 行:线程 [sleeper] 把大部分时间花在 [Thread.sleep] 中。[while (true)] 循环没有退出条件:当线程被中断时,由 [sleep] 抛出的 [InterruptedException] 异常导致循环退出(第 14 行)。lambda 是一条 [try] 语句,涵盖了线程的全部工作:收到异常后,线程显示一条消息,然后终止;
- 第 20–27 行:线程 [calculator] 从不等待。它在每次循环迭代时检查自己的中断标志(第 23 行);
- 第 29–38 行:线程 [deaf] 捕获 [InterruptedException] 并继续运行,就像什么都没发生一样。停止请求丢失了:这是您必须避免的错误。它是一个守护线程,这样程序就可以在不等待它的情况下终止;
- 第 41 行:主线程让其他线程运行一秒钟;
- 第 43–45 行:它请求这三个线程终止;
- 第 47–50 行:它等待每个线程结束,最多等待一秒钟。方法 [join(Duration)] (Java 19)在线程于该时间内结束时返回 [true] ,否则返回 [false] 。[Duration.ofSeconds(1)] 表示一秒钟的时长(类 [java.time.Duration])。
结果:
| > java Threads05.java
19:14:25.674 : sleeper, round 1
19:14:26.228 : sleeper, round 2
19:14:26.605 : Main requests the three threads to stop
19:14:26.606 : deaf ignores the interruption and continues
19:14:26.615 : sleeper interrupted while sleeping, it stops
19:14:26.622 : thread sleeper finished: true
19:14:26.642 : calculator interrupted after 37,667,665 iterations, it stops
19:14:26.742 : thread calculator finished: true
19:14:27.756 : thread deaf finished: false
|
线程 [sleeper] 和 [calculator] 在请求之后几毫秒就终止了;线程 [deaf] 忽略了该请求,一秒钟之后仍未结束([false],最后一行)。calculator 的迭代次数每次运行差异很大,取决于它获得的 CPU 时间份额;结果的其余部分是可重现的。
中断是整个 Java 库用来终止操作的机制:我们稍后会看到,任务的 [cancel] 方法([Future])以及线程池的强制终止([shutdownNow])都会中断受影响的线程。下一章将介绍取消异步处理的其他方式,例如超时。
8.4. 虚拟线程
到目前为止我们创建的线程都是 平台线程:每一个都是对一个操作系统线程的封装,并在其整个生命周期内占用该系统线程。系统线程是一种昂贵的资源:创建它需要时间,它的栈会预留内存(大约一兆字节),而且系统无法高效地管理超过几千个这样的线程。然而,为每个客户端分配一个线程的服务器(见下一段中的图示)大部分时间都在等待:等待数据库的响应、等待客户端的下一个请求……在这些等待期间,系统线程被阻塞而无法使用。
Java 21 引入了 虚拟线程 (“virtual threads”,JEP 444)。虚拟线程与其他任何对象一样是一个 [Thread] 对象,但它由 Java 虚拟机而不是操作系统管理:
- 为了执行,虚拟线程被 挂载 到一个平台线程上,该平台线程称为它的“载体线程”。载体线程构成一个小型的池,其大小默认为处理器的数量;
- 当虚拟线程阻塞时([sleep]、等待网络 I/O、等待锁、阻塞队列等),它会被 卸载:它的栈被存放在虚拟机的内存中,载体线程立即可供另一个虚拟线程使用。当等待结束时,虚拟线程会重新挂载到某个宿主线程上——不一定是原来的那个;
- 一个虚拟线程只占用几百字节:可以创建数百万个。
程序 [Threads06.java] 比较了启动 10,000 个平台线程和 10,000 个虚拟线程,每个线程都休眠一秒钟:
| // 平台线程与虚拟线程(Java 21)
void main() throws InterruptedException {
final int nbThreads = 10_000;
// 两个线程构建器
measure("platform threads", Thread.ofPlatform(), nbThreads);
measure("virtual threads", Thread.ofVirtual(), nbThreads);
// 虚拟线程运行在称为载体线程的平台线程上
Thread virtual = Thread.ofVirtual().name("virtual").start(() -> {
IO.println("Before sleep: " + Thread.currentThread());
sleep(100);
IO.println("After sleep: " + Thread.currentThread());
});
virtual.join();
IO.println("isVirtual: " + virtual.isVirtual() + ", isDaemon: " + virtual.isDaemon());
}
// 启动 [nbThreads] 个休眠 1 秒的线程,等待它们结束并显示总耗时
static void measure(String kind, Thread.Builder builder, int nbThreads) throws InterruptedException {
long start = System.nanoTime();
var threads = new ArrayList<Thread>(nbThreads);
for (int i = 0; i < nbThreads; i++) {
threads.add(builder.start(() -> sleep(1000)));
}
for (Thread thread : threads) {
thread.join();
}
long duration = (System.nanoTime() - start) / 1_000_000;
IO.println("%,d %s slept 1 s each: total duration %,d ms".formatted(nbThreads, kind, duration));
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
|
说明:
- 第 6–7 行:方法 [measure] 被调用两次,第一次使用平台线程构建器([Thread.ofPlatform()]),然后使用虚拟线程构建器([Thread.ofVirtual()])。两种构建器共享公共类型 [Thread.Builder]:其余代码完全相同;
- 第 20–31 行:方法 [measure] 启动 [nbThreads] 个休眠一秒钟的线程,等待它们结束,并显示总时长。方法 [System.nanoTime()] 返回以纳秒为单位的时间,仅用于测量时长;
- 第 10–14 行:一个名为 [virtual] 的虚拟线程在休眠前后显示它的文本表示;
- 第 16 行:虚拟线程始终是守护线程。
结果:
| > java Threads06.java
10,000 platform threads slept 1 s each: total duration 4,518 ms
10,000 virtual threads slept 1 s each: total duration 1,222 ms
Before sleep: VirtualThread[#20026,virtual]/runnable@ForkJoinPool-1-worker-2
After sleep: VirtualThread[#20026,virtual]/runnable@ForkJoinPool-1-worker-2
isVirtual: true, isDaemon: true
|
- 10,000 个平台线程花了好几秒才完成本该只需一秒的工作:创建系统线程和管理它们的栈代价高昂。若有 100,000 个线程,程序很可能会因为内存不足或可用系统线程不足而失败;
- 10,000 个虚拟线程只用了略多于一秒就完成了同样的任务:它们在休眠期间并不占用任何系统线程。具体时间每次运行都不同,但两种线程之间的差异是可重现的;
- 虚拟线程的文本表示([VirtualThread[#…,virtual]])在字符 [@] 之后指出了它所挂载的宿主线程:来自 [ForkJoinPool-1] 池的一个线程,我们稍后会再讨论它。被挂起之后,虚拟线程可以在另一个载体上恢复执行。
虚拟线程不会让计算变快:让处理器一直忙碌而从不等待的计算,在虚拟线程中并不比在平台线程中运行得更快,并发计算的数量仍然受处理器数量的限制。它们的好处在于,可以不计成本地为每个大部分时间都在 等待的任务专门分配一个线程:服务器、下一段以及第 12 章和第 13 章就是这种情况。我们将要讲述的关于线程同步的所有内容,对虚拟线程和平台线程同样适用。
8.5. 线程的好处
既然我们已经强调了存在一个默认线程——执行 [main] 方法的那个线程——并且知道了如何创建其他线程,让我们来考虑线程的好处。它们主要有两种用途:
- 为耗时的计算利用 机器的 所有处理器 :工作被划分成若干块,分配给不同的线程。我们将在本章末尾使用并行流和 [Fork/Join] 框架来做到这一点;
- 同时执行多个任务,尤其是当其中一些任务主要涉及等待(等待网络响应、磁盘读取或用户输入)时。互联网上的客户端/服务器应用程序就是这种情况,我们将在第 12 章讨论。
在客户端/服务器互联网应用程序中,位于机器 S1 上的服务器响应来自远程机器 C1、C2、……、Cn 上的客户端的请求:

我们每天都在使用遵循这种模式的互联网应用程序:Web 服务、电子邮件、文件传输等。在上图中,服务器 S1 必须同时为客户端 Ci 提供服务。以文件服务器为例,我们知道一次传输有时会持续几分钟。绝不能让单个客户端在这么长的时间里独占服务器。一种常见的解决方案是让服务器创建与客户端数量一样多的执行线程。然后每个线程负责处理一个特定的客户端:

使用平台线程时,服务器实际上使用的是 线程池——稍后讨论——其有限的线程数限制了同时服务的客户端数量。使用虚拟线程时,上面的方案再次成为正确的解决方案:每个客户端一个虚拟线程,即使有数万个客户端也是如此,因为处于等待中的客户端不占用任何系统线程。这正是当今现代 Java Web 服务器(如我们将在第 13 章中使用的 Tomcat)所能实现的。
8.6. 线程之间的信息交换
在前面的示例中,线程执行的是无参数的方法,或者是调用带参数方法的 lambda。由于 *[run] 方法(属于 [Runnable] )既没有参数也没有返回值,因此是 lambda 向被启动的线程传递信息:它 捕获 所需的变量。如果被捕获的变量引用一个对象,被启动的线程还可以把结果存放在其中,供启动它的线程读取。程序 [Threads07.java]* 如下:
| // 线程之间交换信息
void main() throws InterruptedException {
// 我们为主线程命名
Thread.currentThread().setName("Main");
// 创建 5 个线程
var tasks = new Thread[5];
var data = new Data[5];
for (int i = 0; i < tasks.length; i++) {
// 与线程交换的对象:启动线程设置开始时间和持续时间
Data d = new Data(LocalTime.now(), i + 1);
data[i] = d;
// 被启动的线程通过捕获该对象的 lambda 表达式接收它
tasks[i] = new Thread(() -> sleep(d), String.valueOf(i));
tasks[i].start();
}
// 我们依次等待各个线程
var format = DateTimeFormatter.ofPattern("HH:mm:ss");
for (int i = 0; i < tasks.length; i++) {
// 等待第 i 号线程结束
tasks[i].join();
// 第 i 号线程已填写其对象的结束时间
Data d = data[i];
double actualDuration = Duration.between(d.getStart(), d.getEnd()).toMillis() / 1000.0;
IO.println("Thread %s finished: start %s, scheduled duration %d s, end %s, actual duration %.3f s"
.formatted(tasks[i].getName(), d.getStart().format(format), d.getDuration(),
d.getEnd().format(format), actualDuration));
}
// 主线程结束
IO.println("End of thread " + Thread.currentThread().getName() + " at " + LocalTime.now().format(format));
}
// 线程执行的方法
static void sleep(Data data) {
try {
// 休眠 [duration] 秒
Thread.sleep(data.getDuration() * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// 被启动的线程向启动线程返回结果
data.setEnd(LocalTime.now());
}
// 启动线程与被启动线程之间交换的信息
static class Data {
// 由启动线程设置
private final LocalTime start;
private final int duration;
// 由被启动线程设置
private LocalTime end;
Data(LocalTime start, int duration) {
this.start = start;
this.duration = duration;
}
LocalTime getStart() {
return start;
}
int getDuration() {
return duration;
}
LocalTime getEnd() {
return end;
}
void setEnd(LocalTime end) {
this.end = end;
}
}
|
说明:
- 第 48–75 行:与每个线程交换的信息是一个 [Data] 对象。启动线程与被启动线程之间存在双向的信息交换。[start] 和 [duration] 是 [final] 字段:它们由构造函数一次性设定:
- [start]:线程开始执行的时间,由启动线程设定;
- [duration]:被启动线程休眠的时长(以秒为单位),由启动线程设定;
- [end]:线程结束执行的时间,由被启动线程设定;
- 第 12 行:创建一个 [Data] 对象,并把它存放在 [data] 数组中(第 13 行);
- 第 15 行:lambda [() -> sleep(d)] 捕获变量 [d],该变量实际上是 final 的:被启动的线程将以对象 [d] 为参数,执行第 36–45 行的方法 [sleep] ;
- 第 21–30 行:主线程等待它所启动的每个线程结束,然后从线程 #i 取回对象 [data[i]] 并显示其内容。实际时长由 [Duration.between(d.getStart(), d.getEnd())] 计算;
- 第 39 行:参数的 [duration] 字段设定休眠时长;
- 第 44 行:参数的 [end] 字段被填充。
结果:
| > java Threads07.java
Thread 0 finished: start 19:14:38, scheduled duration 1 s, end 19:14:39, actual duration 1.005 s
Thread 1 finished: start 19:14:38, scheduled duration 2 s, end 19:14:40, actual duration 2.006 s
Thread 2 finished: start 19:14:38, scheduled duration 3 s, end 19:14:41, actual duration 3.000 s
Thread 3 finished: start 19:14:38, scheduled duration 4 s, end 19:14:42, actual duration 4.000 s
Thread 4 finished: start 19:14:38, scheduled duration 5 s, end 19:14:43, actual duration 5.000 s
End of thread Main at 19:14:43
|
这个示例表明,两个线程可以交换信息:
- 调用线程可以通过向被调用线程提供信息来控制它的执行;
- 被启动的线程可以向启动它的线程返回结果。
为了让调用线程知道它所等待的结果何时可用,必须在被调用线程结束时通知它。这里,它使用 [join] 方法等待线程结束。这不仅仅是时间安排的问题:正如我们将在关于 [volatile] 关键字的一节中看到的,一个线程所做的写操作不一定对另一个线程可见。Java 的内存模型保证,一个线程写入的所有内容,对使用 [join] 等待它结束的线程都是可见的,并且启动线程在 [start] 之前写入的所有内容,对被启动的线程都是可见的。稍后我们将探讨其他同步方式。
除了 lambda,我们还可以编写一个实现 [Runnable] 的类,其字段包含所交换的信息。lambda 更简洁;它是如今最常用的方法。为了取回处理操作的结果,稍后我们还将介绍 [Callable<V>] 接口,其 [V call()] 方法会返回结果。
8.7. 并发访问共享资源
8.7.1. 不同步的并发访问
在上一节中,信息只在两个线程之间、并且只在非常特定的时刻交换:这是参数传递的经典例子。还有其他情况,信息由多个线程共享,而这些线程可能想要同时读取或更新它。这就引出了这些信息的完整性问题。假设共享信息是一个包含各种信息 I1、I2、……、In 的结构 S:
- 线程 T1 开始更新结构 S:它修改了字段 I1,并在完成对结构 S 的完整更新之前被中断;
- 获得处理器的线程 T2 随后读取结构 S 来做决策。它读到的是处于不稳定状态的结构:有些字段是最新的,有些则不是。
这种情形称为对共享资源(这里是结构 S)的并发访问。它往往难以管理。让我们考虑下面的示例,来说明可能出现的问题:
- 应用程序将生成 n 个线程,其中 n 作为参数传入;
- 共享资源是一个计数器,每个被生成的线程都必须对它加一;
- 在应用程序结束时,显示计数器的值。因此它应该等于 n。
程序 [Threads08.java] 如下:
| // 对共享资源的非同步并发访问
void main(String[] args) throws InterruptedException {
// 检查参数:要创建的线程数
final int nbMaxThreads = 100;
int nbThreads = args.length == 1 ? integer(args[0]) : -1;
if (nbThreads < 1 || nbThreads > nbMaxThreads) {
System.err.println("syntax: java Threads08.java nbThreads"
+ " (nbThreads between 1 and " + nbMaxThreads + ")");
System.exit(1);
}
// 创建并启动线程
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = new Thread(Counter::increment, String.valueOf(i));
threads[i].start();
}
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
// 显示计数器
IO.println("Number of threads generated: " + Counter.getValue());
}
// [text] 中包含的整数,如果无效则为 -1
static int integer(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return -1;
}
}
// 共享资源
static class Counter {
// 线程计数器,由所有线程共享
private static int value;
static int getValue() {
return value;
}
// 每个线程执行的方法
static void increment() {
String name = Thread.currentThread().getName();
// 读取计数器
int v = value;
IO.println("At " + time() + ", thread " + name + " read the counter value: " + v);
// 等待:线程让出处理器
sleep(1000);
// 递增计数器
value = v + 1;
IO.println("At " + time() + ", thread " + name + " wrote the counter value: "
+ value);
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5–11 行:线程的数量作为参数传入。方法 [integer] (第 28–34 行)返回字符串中包含的整数,如果字符串中没有整数则返回 -1;因此第 7 行的条件会同时拒绝缺失或无效的参数以及超出 [1, 100] 范围的数字。如果出错,程序会向错误输出([System.err])写一条消息,并以退出码 1 终止([System.exit(1)]);
- 第 16 行:每个线程执行静态方法 [increment] ,该方法属于类 [Counter]。方法引用 [Counter::increment] 在这里是有效的,因为 [Counter] 是一个具名类;
- 第 37–58 行:共享资源是静态字段 [value] ,属于类 [Counter]。计数器被封装在一个静态嵌套类中,每个线程执行的是方法 [increment] ;
- 第 49 行:读取计数器;
- 第 52 行:线程暂停 1 秒。因此它失去了 CPU;
- 第 54 行:计数器加一。
一秒钟的暂停只是为了迫使线程在读取和写入计数器之间失去 CPU。实际上,并不能保证线程在这两个时刻之间不会被中断,而且在多处理器机器上,两个线程甚至可能在完全相同的时刻读取计数器。一秒钟的暂停只是把这种风险系统化了。
程序参数放在源文件名之后。没有参数时,会显示一条错误消息(Linux shell 命令 ***[echo $?]*** 显示最后一个执行的程序的退出码):
| > java Threads08.java
syntax: java Threads08.java nbThreads (nbThreads between 1 and 100)
> echo $?
1
|
使用 5 个线程:
| > java Threads08.java 5
At 19:14:46.240, thread 1 read the counter value: 0
At 19:14:46.244, thread 3 read the counter value: 0
At 19:14:46.246, thread 4 read the counter value: 0
At 19:14:46.247, thread 0 read the counter value: 0
At 19:14:46.237, thread 2 read the counter value: 0
At 19:14:47.244, thread 1 wrote the counter value: 1
At 19:14:47.245, thread 3 wrote the counter value: 1
At 19:14:47.247, thread 4 wrote the counter value: 1
At 19:14:47.247, thread 0 wrote the counter value: 1
At 19:14:47.252, thread 2 wrote the counter value: 1
Number of threads generated: 1
|
看这些结果,就能清楚地知道发生了什么:
- 第一个线程读取计数器,发现是 0。它暂停 1 秒,从而失去了 CPU;
- 第二个线程也读取计数器的值。它仍然是 0,因为前一个线程尚未对它加一。它同样暂停 1 秒;
- 在不到一秒的时间里,全部 5 个线程都来得及读到值 0;
- 当它们醒来时,各自对所读到的值 0 加一,并且都向计数器写入值 1,最后一行(第 12 行)证实了这一点。这个错误的结果是可重现的:每次执行变化的只是线程的顺序。
有人可能会反驳说这个示例是人为设计的。那么让我们去掉休眠,并使用运算符 [++], 它给人以单条指令的错觉。程序 [Threads09.java] 如下:
| // 不休眠时的更新丢失:counter++ 不是原子操作
void main(String[] args) throws InterruptedException {
// 参数:线程数,每个线程的递增次数
int nbThreads = args.length > 0 ? Integer.parseInt(args[0]) : 4;
int nbIncrements = args.length > 1 ? Integer.parseInt(args[1]) : 50_000_000;
// 我们将实验重复三次
for (int attempt = 1; attempt <= 3; attempt++) {
Counter.value = 0;
// 创建并启动线程
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = Thread.ofPlatform().start(() -> {
for (int j = 0; j < nbIncrements; j++) {
// 读取、递增、写入:三个操作
Counter.value++;
}
});
}
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
// 结果
int expected = nbThreads * nbIncrements;
IO.println("Attempt %d: expected value %,d, obtained value %,d, lost updates %,d"
.formatted(attempt, expected, Counter.value, expected - Counter.value));
}
}
// 共享资源
static class Counter {
static int value;
}
|
说明:
- 第 5–6 行:线程数量(默认为 4)和每个线程执行的递增次数(默认为 5000 万)可以作为参数传入。分隔符 [_] 使常量 [50_000_000] 更易读;
- 第 14 行:线程由 [Thread.ofPlatform().start(…)] 创建并启动;它们不需要名称;
- 第 17 行:每个线程不暂停地对共享计数器递增;
- 第 27 行:在格式字符串中,[%,d] 使用当前语言的千位分隔符显示整数(这里是英语:逗号)。字符串的实例方法 [formatted(…)] (Java 15)等价于 [String.format(string, …)]。
结果:
| > java Threads09.java
Attempt 1: expected value 200,000,000, obtained value 132,308,591, lost updates 67,691,409
Attempt 2: expected value 200,000,000, obtained value 135,621,476, lost updates 64,378,524
Attempt 3: expected value 200,000,000, obtained value 50,000,635, lost updates 149,999,365
|
丢失了数千万次更新,而且这个数字每次测试都不相同。高级操作 [Counter.value++] 实际上会被翻译成若干条基本的处理器指令:从内存读取值,在寄存器中递增它,再把结果写回内存。如果两个线程在其中一个写入自己的结果之前读取了同一个值,就会丢失一次递增,这与前面的示例完全一样。
测试 3 值得解释一下:它丢失了几乎恰好 1.5 亿次更新,相当于四个线程中三个线程的工作量。执行几秒钟之后,虚拟机的即时编译器(JIT)优化了第 15–18 行的循环:它判定在循环期间没有其他线程应该看到该计数器(代码中没有任何东西要求这样做),于是把计数器放进了处理器寄存器。于是每个线程只读取一次计数器,在寄存器中给它加上 5000 万,最后再写回一次。如果四个线程在其中任何一个写入之前都读到了值 0,那么四个结果中有三个会丢失;反之,如果它们的工作没有重叠,结果就是正确的。在这个程序的其他几次运行中,测试 2 和测试 3 实际上得到了精确的值 200,000,000。只有在这一优化之前运行的第一个测试始终会丢失更新。这正是这类错误如此危险的原因:程序可以运行数月,然后恰恰在机器负载更重或运行更快的那一天出错。
问题出在哪里?一个线程读取了过期的值,因为另一个线程在完成更新计数器的任务之前被中断了——或者正在另一个处理器上同时工作。这就引出了程序中的临界资源和临界区的概念:
- 临界资源 是一次只能被一个线程持有的资源。这里的临界资源是计数器;
- 程序的 临界区 是线程执行流中的一段指令序列,线程在其间访问临界资源。我们必须确保,在这个临界区内,该线程是唯一能访问该资源的线程。
在程序 [Threads08.java] 中,临界区是读取计数器与写入其新值之间的代码:
| // 读取计数器
int v = value;
IO.println("At " + time() + ", thread " + name + " read the counter value: " + v);
// 等待:线程让出处理器
sleep(1000);
// 递增计数器
value = v + 1;
|
要执行这段代码,必须保证线程是唯一在运行的线程。它可以被中断,但在中断期间,不能有其他线程执行同一段代码。Java 提供了各种工具来确保单线程进入代码的临界区。我们现在来看其中的几种。
8.7.2. synchronized 关键字
代码块 [synchronized] 按如下方式界定临界区:[synchronized (lock) { …critical section… }]***。[lock]* 是对所有执行该临界区的线程都可见的对象。在 Java 中,每个对象 都有一个内部锁,也称为 监视器。[synchronized] 代码块确保一次只有一个线程持有对象 [lock] 的监视器,也就是说一次只有一个线程执行临界区:遇到被其他线程持有的监视器的线程会被阻塞,直到该监视器被释放。退出代码块时(无论是正常退出还是因异常而退出)都会释放监视器。
前面的示例在 [Threads10.java] 中改写如下:
| // 由 synchronized 块保护的临界区
void main(String[] args) throws InterruptedException {
// 检查参数:要创建的线程数
final int nbMaxThreads = 100;
int nbThreads = args.length == 1 ? integer(args[0]) : -1;
if (nbThreads < 1 || nbThreads > nbMaxThreads) {
System.err.println("syntax: java Threads10.java nbThreads"
+ " (nbThreads between 1 and " + nbMaxThreads + ")");
System.exit(1);
}
// 创建并启动线程
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = new Thread(Counter::increment, String.valueOf(i));
threads[i].start();
}
// 按创建的相反顺序等待线程结束
Thread.currentThread().setName("Main");
for (int i = nbThreads - 1; i >= 0; i--) {
IO.println("At " + time() + ", thread Main waits for the end of thread " + threads[i].getName());
threads[i].join();
IO.println("At " + time() + ", thread Main was notified of the end of thread "
+ threads[i].getName());
}
// 显示计数器
IO.println("Number of threads generated: " + Counter.getValue());
}
// [text] 中包含的整数,如果无效则为 -1
static int integer(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return -1;
}
}
// 共享资源
static class Counter {
// 线程计数器
private static int value;
// 同步对象,对所有线程可见
private static final Object lock = new Object();
static int getValue() {
synchronized (lock) {
return value;
}
}
// 每个线程执行的方法
static void increment() {
String name = Thread.currentThread().getName();
IO.println("At " + time() + ", thread " + name
+ " waits for permission to enter the critical section");
// 同一时刻只有一个线程执行下面的块
synchronized (lock) {
// 读取计数器
int v = value;
IO.println("At " + time() + ", thread " + name + " read the counter value: " + v);
// 等待:线程让出处理器,但保持持有锁
sleep(1000);
// 递增计数器
value = v + 1;
IO.println("At " + time() + ", thread " + name + " wrote the counter value: "
+ value);
}
IO.println("At " + time() + ", thread " + name + " left the critical section");
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 45 行:[lock] 是将使所有线程同步的对象。它没有其他用途:它只是一个简单的 [Object]。它是 [final] 的:该引用决不能改变,否则两个线程可能会锁住两个不同的对象;
- 第 59–69 行:[increment] 方法的临界区被 [synchronized] 代码块包围。线程在休眠一秒钟期间一直持有锁:其他线程无法进入;
- 第 47–51 行:主线程对计数器的读取同样受锁保护。在这里这并非严格必要,因为主线程已经通过 [join] 等待其他线程结束;但这是良好的实践:受锁保护的数据必须在该锁的保护下读写;
- 第 20–26 行:主线程按线程创建的相反顺序等待它们。
使用 3 个线程的结果:
| > java Threads10.java 3
At 19:14:50.140, thread 2 waits for permission to enter the critical section
At 19:14:50.147, thread 2 read the counter value: 0
At 19:14:50.140, thread 1 waits for permission to enter the critical section
At 19:14:50.140, thread 0 waits for permission to enter the critical section
At 19:14:50.133, thread Main waits for the end of thread 2
At 19:14:51.151, thread 2 wrote the counter value: 1
At 19:14:51.152, thread 1 read the counter value: 1
At 19:14:51.153, thread 2 left the critical section
At 19:14:51.153, thread Main was notified of the end of thread 2
At 19:14:51.153, thread Main waits for the end of thread 1
At 19:14:52.160, thread 1 wrote the counter value: 2
At 19:14:52.160, thread 0 read the counter value: 2
At 19:14:52.160, thread 1 left the critical section
At 19:14:52.162, thread Main was notified of the end of thread 1
At 19:14:52.162, thread Main waits for the end of thread 0
At 19:14:53.160, thread 0 wrote the counter value: 3
At 19:14:53.160, thread 0 left the critical section
At 19:14:53.161, thread Main was notified of the end of thread 0
Number of threads generated: 3
|
- 三个线程几乎在同一时间请求进入临界区;
- 只有一个线程进入——这里是线程 2(进入的顺序没有保证:不一定是最先到达的最先进入)。它读取计数器,休眠一秒钟,写入新值,然后退出临界区;
- 另外两个线程被阻塞,直到第一个线程退出临界区,然后一个接一个地继续。每个线程读取的都是前一个线程写入的值。请注意(第 8–9 行),线程 1 在线程 2 表示它已退出临界区之前就读取了 计数器:线程 2 确实已经释放了锁,但它直到 [synchronized] 代码块之后才显示它的消息,而线程 1 更快;
- 主线程一直在等待线程 2 结束。当得到线程 2 已结束的通知后,它等待线程 1 结束,然后等待线程 0 结束;
- 线程数量是正确的(第 20 行)。无论线程以什么顺序运行,这个结果都是可重现的。
关键字 [synchronized] 也可以应用于整个方法:[synchronized void m() {…}] 等价于包含方法整个主体的代码块 [synchronized (this) {…}] ,而 [static synchronized void m() {…}] 则等价于代码块 [synchronized (Counter.class) {…}],它锁定类对象 [Class]。这是最简短的写法,也很常用。然而,它有一个缺点:被锁定的对象([this],或 [Class] 对象)从外部是可见的,外部代码可以获取同一个锁并阻塞我们的代码。因此,通常更可取的是像示例中那样锁定一个 私有 对象。出于同样的原因,我们从不锁定字符串(相同的字符串字面量是整个程序共享的同一个对象),也不锁定——自 Java 16 起——“基于值”的类的对象,例如 [Integer] 或 [LocalDate](编译器会对此发出警告)。
已经持有某个监视器的线程可以在同一个对象上重新进入 [synchronized] 代码块而不会阻塞自己:这种锁称为 可重入锁。因此,[synchronized] 方法可以调用同一对象上的另一个 [synchronized] 方法。
8.7.3. ReentrantLock 类
[synchronized] 锁简单但不灵活:等待监视器的线程会无限期等待,既不能在一定时间后放弃,也不能被中断。[java.util.concurrent.locks.ReentrantLock] 类(Java 5)是一种显式锁——它同样是可重入的——提供了这些能力。它实现了 [Lock] 接口。我们将使用下面的构造函数和方法:
成员 | 作用 |
[ReentrantLock()], [ReentrantLock(boolean fair)] | 创建一个锁。公平锁([true])按线程请求锁的顺序授予它;非公平锁(默认)更快,但线程可能插队到其他线程前面 |
[void lock()] | 正在执行 [V.lock()], 的线程 T1 请求锁 V。如果 V 没有被任何线程持有,它就被授予 T1。如果线程 T2 随后执行同样的操作,它就会被阻塞:一个锁只能属于一个线程。当 T1 释放 V 时,T2 会被解除阻塞。因此,可能有多个线程在等待 V 时被阻塞 |
[boolean tryLock()], [boolean tryLock(long timeout, TimeUnit unit)] | 立即请求锁,或者最多等待 [timeout] 的时间来请求锁。该方法返回 [false] 表示未能获得锁 |
[void lockInterruptibly()] | 类似于 [lock],但等待可以被中断([InterruptedException]) |
[void unlock()] | 持有 V 的线程释放它。随后,等待 V 的线程之一获得它 |
[boolean isHeldByCurrentThread()] | 指示当前线程是否持有该锁 |
[Condition newCondition()] | 创建与该锁关联的条件(见下文) |
临界区的同步总是遵循同一种模式:[V.lock(); try { …critical section… } finally { V.unlock(); }]。不要忘记释放锁;否则,等待该锁的线程将一直被阻塞:这就是为什么要在 [finally] 子句中释放锁,无论是否发生异常,该子句都会被执行。[synchronized] 代码块会自动完成这件事;而使用 [ReentrantLock] 时,则由程序员负责。[Threads11.java] 程序用 [ReentrantLock] 延续了前面的示例:
| // 由 ReentrantLock 保护的临界区
void main(String[] args) throws InterruptedException {
// 检查参数:要创建的线程数
final int nbMaxThreads = 100;
int nbThreads = args.length == 1 ? integer(args[0]) : -1;
if (nbThreads < 1 || nbThreads > nbMaxThreads) {
System.err.println("syntax: java Threads11.java nbThreads"
+ " (nbThreads between 1 and " + nbMaxThreads + ")");
System.exit(1);
}
// 创建并启动线程
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = new Thread(Counter::increment, String.valueOf(i));
threads[i].start();
}
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
// 显示计数器
IO.println("Number of threads generated: " + Counter.getValue());
}
// [text] 中包含的整数,如果无效则为 -1
static int integer(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return -1;
}
}
// 共享资源
static class Counter {
// 线程计数器
private static int value;
// 同步对象:公平锁(true)
private static final ReentrantLock lock = new ReentrantLock(true);
static int getValue() {
lock.lock();
try {
return value;
} finally {
lock.unlock();
}
}
// 每个线程执行的方法
static void increment() {
String name = Thread.currentThread().getName();
IO.println("At " + time() + ", thread " + name
+ " waits for permission to enter the critical section");
// 我们请求锁
lock.lock();
try {
// 读取计数器
int v = value;
IO.println("At " + time() + ", thread " + name + " read the counter value: " + v);
// 等待
sleep(1000);
// 递增计数器
value = v + 1;
IO.println("At " + time() + ", thread " + name + " wrote the counter value: "
+ value);
} finally {
// 无论是否发生异常,我们都释放锁
IO.println("At " + time() + ", thread " + name + " leaves the critical section");
lock.unlock();
}
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
主程序与 [Threads08.java] 的相同。说明:
- 第 41 行:线程同步对象现在是一个公平锁 [ReentrantLock];
- 第 58 行:临界区开始。线程被阻塞,直到锁被释放;
- 第 59–73 行:由于无论是否发生异常,锁都必须被释放,因此临界区被放在一个 [try] 中,其 [finally] 子句释放锁(第 72 行);
- 第 43–50 行:同样的模式保护着对计数器的读取。[return value;] 语句在 [finally] 子句之前执行:返回的值是在持有锁时读取的。
结果:
| > java Threads11.java 3
At 19:14:55.022, thread 1 waits for permission to enter the critical section
At 19:14:55.025, thread 1 read the counter value: 0
At 19:14:55.020, thread 2 waits for permission to enter the critical section
At 19:14:55.020, thread 0 waits for permission to enter the critical section
At 19:14:56.027, thread 1 wrote the counter value: 1
At 19:14:56.027, thread 1 leaves the critical section
At 19:14:56.027, thread 2 read the counter value: 1
At 19:14:57.028, thread 2 wrote the counter value: 2
At 19:14:57.028, thread 2 leaves the critical section
At 19:14:57.028, thread 0 read the counter value: 2
At 19:14:58.028, thread 0 wrote the counter value: 3
At 19:14:58.028, thread 0 leaves the critical section
Number of threads generated: 3
|
结果与前面的相似:线程逐个进入临界区,最终的计数器值是正确的。由于锁是公平的,线程是按它们请求锁的顺序获得锁的:即它们调用 [lock] 的顺序,而“等待许可”消息的时间戳(是稍早计算的)只是对该顺序的近似。
什么时候应该使用 [ReentrantLock] 而不是 [synchronized]?当您需要它的某个额外特性时:超时([tryLock],我们将用它来防止死锁)、可中断的等待、公平性或多个条件。否则,[synchronized] 代码块——更简单,并且消除了忘记 [unlock] 的风险——就工作得很好。自 Java 24 起,它在虚拟线程上不再造成任何问题:此前,阻塞在 [synchronized] 代码块中的虚拟线程无法释放它的宿主线程,这使得 [ReentrantLock] 成为首选。
8.7.4. 同步进程:文件锁
上面描述的锁用于同步同一个虚拟机内的线程——即同一个进程内的线程。有时不同的进程需要共享某个资源,比如文件,或者您可能想防止同一个应用程序的两个实例被启动。Java 没有提供跨进程共享的具名同步对象;取而代之的是使用由操作系统管理的 文件锁 :即 [java.nio.channels.FileLock] 类。锁是在以 [FileChannel] 通道形式打开的文件上获得的:
- [FileLock lock()]:等待锁变为可用并获取它;
- [FileLock tryLock()]:尝试不等待地获取锁,如果锁被其他进程持有,则返回 [null] ;
- [void release()]:释放锁。当通道关闭或进程结束时(即使是被突然终止),锁也会被释放:锁不可能一直“被遗弃”。
程序 [Threads12.java] 在两个不同的进程中被启动两次,这两个进程共享一个临界区:
| // 文件锁可以同步不同的进程
void main(String[] args) throws IOException, InterruptedException {
// 被锁定的文件为所有使用它的进程所知
Path file = Path.of(System.getProperty("java.io.tmpdir"), "java-course-threads-12.lock");
// 进程的名称作为参数传入
String process = args.length > 0 ? args[0] : "P";
// 我们打开文件(如果尚不存在则创建)
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
IO.println(time() + " : process " + process + " requests the lock");
// 不等待的尝试:如果另一个进程持有锁则返回 null
FileLock lock = channel.tryLock();
if (lock == null) {
IO.println(time() + " : the lock is held by another process, " + process + " waits");
// 无时间限制地等待
lock = channel.lock();
}
try {
// 进程之间的临界区
IO.println(time() + " : process " + process + " obtained the lock, it works for 3 s");
Thread.sleep(3000);
IO.println(time() + " : process " + process + " releases the lock");
} finally {
lock.release();
}
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5 行:用作锁的文件。所有锁定该文件的进程彼此同步。它被放在系统的临时文件夹中,该文件夹由系统属性 [java.io.tmpdir] 指定(在 Linux 上为 [/tmp] )。它的内容无关紧要:可以保持为空;
- 第 10 行:文件以写入方式打开(独占锁需要这样),如果尚不存在则创建([CREATE])。带资源的 [try] 语句会在结束时关闭通道;
- 第 13 行:进程尝试不等待地获取锁。如果失败,它会报告失败,然后无限期地等待锁(第 17 行);
- 第 19–26 行:临界区,持续 3 秒,随后释放锁。
文件锁属于整个进程,而不是单个线程:它不用于同步同一进程内的线程(在同一进程内对同一个文件两次请求锁会引发 [OverlappingFileLockException] 异常)。我们启动进程 A,等待 1.5 秒,然后在第二个终端中启动进程 B。进程 A 的结果:
| > java Threads12.java A
19:15:04.965 : process A requests the lock
19:15:04.976 : process A obtained the lock, it works for 3 s
19:15:07.976 : process A releases the lock
|
进程 B 的结果:
| > java Threads12.java B
19:15:06.394 : process B requests the lock
19:15:06.405 : the lock is held by another process, B waits
19:15:07.977 : process B obtained the lock, it works for 3 s
19:15:10.978 : process B releases the lock
|
进程 B 遇到了被进程 A 持有的锁,于是进行等待。它在 A 释放锁的那一刻就获得了锁。这种机制的一个常见用途是防止同一个应用程序的两个实例被启动:第二个实例无法通过 [tryLock] 获得锁,会立即终止。
8.7.5. 屏障:Semaphore 类
信号量 是 许可 (或名额)的计数器。[java.util.concurrent.Semaphore] 类提供以下方法:
成员 | 作用 |
[Semaphore(int permits)], [Semaphore(int permits, boolean fair)] | 创建一个具有 [permits] 个许可的信号量;第二个参数的含义与 [ReentrantLock] 相同 |
[void acquire()] | 获取一个许可。如果没有剩余许可,线程会被阻塞,直到有许可被释放。等待可以被中断([InterruptedException]) |
[void acquireUninterruptibly()] | 与上面相同,但等待不能被中断 |
[boolean tryAcquire()], [boolean tryAcquire(long timeout, TimeUnit unit)] | 立即获取许可,或者最多在 [timeout] 内获取;则返回 [false] 表示尝试失败 |
[void release()] | 归还(增加)一个许可;等待中的线程之一随后可以获取它 |
[int availablePermits()] | 可用许可的数量 |
与锁不同,许可不属于任何特定的线程:任何线程都可以调用 [release],即使它从未获取过许可。因此,用 零个 许可创建的信号量是一道关闭的屏障,调用 [acquire] 的线程会在这里被阻塞。另一个线程会在合适的时候通过调用 [release] 来打开它。这个时机完全取决于要解决的问题。获取了唯一许可的线程通过了屏障,屏障随后在它身后关闭;通过归还许可,它为另一个线程打开屏障。如果在前面的示例中,我们用这样的屏障取代锁,代码就变成下面这样([Threads13.java]):
| // 由屏障保护的临界区:只有一个许可的信号量
void main(String[] args) throws InterruptedException {
// 检查参数:要创建的线程数
final int nbMaxThreads = 100;
int nbThreads = args.length == 1 ? integer(args[0]) : -1;
if (nbThreads < 1 || nbThreads > nbMaxThreads) {
System.err.println("syntax: java Threads13.java nbThreads"
+ " (nbThreads between 1 and " + nbMaxThreads + ")");
System.exit(1);
}
// 创建并启动线程
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = new Thread(Counter::increment, String.valueOf(i));
threads[i].start();
}
// 我们让线程到达关闭的屏障前
Thread.sleep(500);
// 我们打开临界区的屏障
Thread.currentThread().setName("Main");
IO.println("At " + time() + ", thread Main opens the barrier of the critical section");
Counter.synchro.release();
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
// 显示计数器
IO.println("Number of threads generated: " + Counter.getValue());
}
// [text] 中包含的整数,如果无效则为 -1
static int integer(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return -1;
}
}
// 共享资源
static class Counter {
// 线程计数器
private static int value;
// 屏障:创建时没有任何许可的信号量,因此是关闭的
static final Semaphore synchro = new Semaphore(0);
static int getValue() {
return value;
}
// 每个线程执行的方法
static void increment() {
String name = Thread.currentThread().getName();
IO.println("At " + time() + ", thread " + name
+ " waits for permission to enter the critical section");
// 通过屏障:线程取走唯一的许可,屏障在其身后关闭
synchro.acquireUninterruptibly();
try {
// 读取计数器
int v = value;
IO.println("At " + time() + ", thread " + name + " read the counter value: " + v);
// 等待
sleep(1000);
// 递增计数器
value = v + 1;
IO.println("At " + time() + ", thread " + name + " wrote the counter value: "
+ value);
} finally {
// 我们归还许可:屏障为另一个线程打开
IO.println("At " + time() + ", thread " + name + " leaves the critical section");
synchro.release();
}
}
}
|
说明:
- 第 47 行:屏障以关闭状态创建。它将由主线程在第 24 行打开;
- 第 20 行:主线程等待半秒钟,让各线程有时间到达屏障;
- 第 59 行:负责递增计数器的线程请求进入临界区的许可。各个线程聚集在关闭的屏障前。当主线程打开它时,等待中的线程之一通过,屏障随即再次关闭。方法 [acquireUninterruptibly] 使我们在这里无需处理异常 [InterruptedException];
- 第 73 行:线程完成工作后,重新打开屏障,让另一个线程进入。
结果:
| > java Threads13.java 3
At 19:15:00.034, thread 1 waits for permission to enter the critical section
At 19:15:00.048, thread 2 waits for permission to enter the critical section
At 19:15:00.041, thread 0 waits for permission to enter the critical section
At 19:15:00.532, thread Main opens the barrier of the critical section
At 19:15:00.533, thread 1 read the counter value: 0
At 19:15:01.535, thread 1 wrote the counter value: 1
At 19:15:01.535, thread 1 leaves the critical section
At 19:15:01.535, thread 2 read the counter value: 1
At 19:15:02.536, thread 2 wrote the counter value: 2
At 19:15:02.536, thread 2 leaves the critical section
At 19:15:02.536, thread 0 read the counter value: 2
At 19:15:03.536, thread 0 wrote the counter value: 3
At 19:15:03.536, thread 0 leaves the critical section
Number of threads generated: 3
|
结果与前面的相似。我们可以看到,三个线程在屏障处等待,直到主线程把它打开(第 5 行)。
8.7.6. CountDownLatch 和 Semaphore 类
同步工具还有两种补充前面示例的用法。
[java.util.concurrent.CountDownLatch] 对象是一个 计数器:它以初始值 N 创建;每次调用它的 [countDown] 方法就使其减一;它的 [await] 方法会阻塞调用线程,直到计数器变为 0。一旦变为 0,它就保持为 0:屏障永久打开,允许所有线程通过。当 N = 1 时,它充当赛跑的“发令信号”;当 N = 作业数量时,它是等待 N 个作业全部完成的一种方式,每个作业在结束时调用 [countDown] 。程序 [Threads14.java] 如下:
| // CountDownLatch:释放所有等待线程的启动信号
void main() throws InterruptedException {
// 启动信号:从 1 开始的倒计时
var start = new CountDownLatch(1);
// 创建并启动 4 个线程
var threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = Thread.ofPlatform().name(String.valueOf(i)).start(() -> {
String name = Thread.currentThread().getName();
IO.println(time() + " : runner " + name + " waits for the start signal");
try {
// 等待倒计时归零
start.await();
IO.println(time() + " : runner " + name + " has started");
} catch (InterruptedException e) {
IO.println(time() + " : runner " + name + " gave up");
}
});
}
// 主线程等待 1 秒,然后发出启动信号
Thread.sleep(1000);
IO.println(time() + " : start signal");
// 倒计时归零:所有等待的线程被释放
start.countDown();
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
IO.println("Value of the countdown: " + start.getCount());
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5 行:倒计时从 1 开始:闸门是关闭的;
- 第 15 行:每个线程等待倒计时变为 0。[await] 方法可能抛出 [InterruptedException];如果线程在等待时被中断,它就退出比赛(第 18 行);
- 第 27 行:主线程在一秒钟之后把倒计时减一;它变为 0;
- 第 32 行:[getCount] 方法返回倒计时的当前值。
结果:
| > java Threads14.java
19:15:14.328 : runner 2 waits for the start signal
19:15:14.328 : runner 0 waits for the start signal
19:15:14.323 : runner 1 waits for the start signal
19:15:14.329 : runner 3 waits for the start signal
19:15:15.293 : start signal
19:15:15.294 : runner 0 has started
19:15:15.296 : runner 1 has started
19:15:15.296 : runner 3 has started
19:15:15.296 : runner 2 has started
Value of the countdown: 0
|
四名跑者在发令信号之后一起起跑,彼此相差只有几毫秒。[CountDownLatch] 只能使用一次;[CyclicBarrier] 类提供可重复使用的会合点(N 个线程相互等待,然后一起出发),而 [Phaser] 类则对这两种工具做了推广。
让我们回到信号量最常见的用法:具有 N 个许可的信号量允许一次最多 N 个线程进入某段代码。这对于限制对数量有限的资源(数据库连接、对服务器的并发请求等)的访问很有用。程序 [Threads15.java] 如下:
| // Semaphore:一段代码中同一时刻最多有 N 个线程
void main() throws InterruptedException {
// 一个有 2 个许可(2 个名额)的信号量
var semaphore = new Semaphore(2);
// 创建并启动 5 个线程
var threads = new Thread[5];
for (int i = 0; i < threads.length; i++) {
threads[i] = Thread.ofPlatform().name(String.valueOf(i)).start(() -> {
String name = Thread.currentThread().getName();
IO.println(time() + " : thread " + name + " waits for a place");
// 我们请求一个名额:如果没有剩余则阻塞
semaphore.acquireUninterruptibly();
try {
IO.println(time() + " : thread " + name + " obtained a place (free places: "
+ semaphore.availablePermits() + ")");
// 工作
sleep(1000);
} finally {
// 我们归还名额
IO.println(time() + " : thread " + name + " releases its place");
semaphore.release();
}
});
}
// 等待线程结束
for (Thread thread : threads) {
thread.join();
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5 行:信号量有 2 个许可:2 个名额;
- 第 14 行:线程请求一个名额。如果有可用的,它就取走并继续;否则它会被阻塞,直到有名额可用;
- 第 17 行:仍然可用的名额数量;
- 第 23 行:线程在 [finally] 子句中归还它的名额。
结果:
| > java Threads15.java
19:15:16.772 : thread 0 waits for a place
19:15:16.773 : thread 0 obtained a place (free places: 1)
19:15:16.776 : thread 3 waits for a place
19:15:16.776 : thread 3 obtained a place (free places: 0)
19:15:16.770 : thread 2 waits for a place
19:15:16.768 : thread 1 waits for a place
19:15:16.767 : thread 4 waits for a place
19:15:17.774 : thread 0 releases its place
19:15:17.775 : thread 2 obtained a place (free places: 0)
19:15:17.776 : thread 3 releases its place
19:15:17.777 : thread 1 obtained a place (free places: 0)
19:15:18.775 : thread 2 releases its place
19:15:18.777 : thread 4 obtained a place (free places: 0)
19:15:18.777 : thread 1 releases its place
19:15:19.780 : thread 4 releases its place
|
所有五个线程都请求名额;两个立即获得,而另外三个等待。每当一个线程释放它的名额,就有一个等待中的线程获得它。代码段中从来不会有超过两个线程。单许可信号量的作用就像一把锁,如同程序 [Threads13.java] 中那样。对于虚拟线程,信号量是限制并发的自然工具:不去限制线程的数量,而是为每个任务创建一个虚拟线程,并用信号量来限制同时使用稀缺资源的任务数量。
8.7.7. 写入可见性:volatile 关键字
锁并不只是用来使一组操作不可分割。它们还解决了第二个更隐蔽的问题:写入的 可见性 。为了加快速度,处理器会把值存储在它的寄存器和缓存中,而编译器会即时地重排或消除读写操作,正如我们在程序 [Threads09.java] 中看到的那样。因此,一个线程写入的值可能要过一段时间才会被另一个线程看到——或者可能永远都看不到。
Java 内存模型 精确地定义了何时保证写入是可见的:当写入与读取之间存在“happens-before”关系时。主要的几种如下:
- 线程在释放锁([synchronized] 代码块结束、[unlock])之前所做的一切,对随后获取该锁的线程都是可见的;
- 调用线程在 [start] 之前所做的一切对被调用线程可见;一个线程所做的一切,对通过 [join] 等待它结束的线程可见;
- 对 [volatile] 字段的写入,对该字段随后的任何读取都是可见的;
- [java.util.concurrent] 中的工具提供类似的保证:线程在 [release()]、[countDown()], 或向并发集合插入元素之前所做的一切,对随后执行 [acquire()]、[await()], 或移除该元素的线程都是可见的。
当这些关系都不存在时,就称该程序包含“数据竞争”,并且没有任何保证。程序 [Threads16.java] 用一个常见的场景来说明这一点:用一个标志来指示线程停止。
| // 线程之间写入的可见性:volatile 关键字
void main() throws InterruptedException {
// 1 - 停止标志是普通字段
Thread t1 = Thread.ofPlatform().name("T1").daemon().start(() -> {
long rounds = 0;
while (!Flags.stop) {
rounds++;
}
IO.println(time() + " : T1 saw the stop request after %,d rounds".formatted(rounds));
});
// 2 - 停止标志是 volatile 字段
Thread t2 = Thread.ofPlatform().name("T2").daemon().start(() -> {
long rounds = 0;
while (!Flags.volatileStop) {
rounds++;
}
IO.println(time() + " : T2 saw the stop request after %,d rounds".formatted(rounds));
});
// 我们让线程运行一秒
Thread.sleep(1000);
IO.println(time() + " : Main requests T1 and T2 to stop");
Flags.stop = true;
Flags.volatileStop = true;
// 等待两个线程结束,每个最多等待 2 秒
for (Thread thread : List.of(t2, t1)) {
boolean finished = thread.join(Duration.ofSeconds(2));
IO.println(time() + " : " + thread.getName() + " finished: " + finished);
}
}
// 停止标志,由各线程共享
static class Flags {
// 普通字段:线程可能永远看不到新值
static boolean stop;
// volatile 字段:任何写入对其后的读取都是可见的
static volatile boolean volatileStop;
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5–11 行:只要普通字段 [Flags.stop] 等于 [false],线程 T1 就一直运行;
- 第 13–19 行:线程 T2 对字段 [volatile] 和 [Flags.volatileStop] 做同样的事;
- 第 24–25 行:一秒钟之后,主线程把两个标志都设为 [true];
- 第 27–30 行:它对这两个线程各等待不超过 2 秒。两个线程都是守护线程,这样即使其中一个仍在运行,程序也可以终止;
- 第 34–39 行:这两个标志。关键字 [volatile] (第 38 行)指定,对该字段的任何读操作都必须从内存中读取,任何写操作都必须立即执行。
结果:
| > java Threads16.java
19:15:23.635 : Main requests T1 and T2 to stop
19:15:23.677 : T2 saw the stop request after 315,278,741 rounds
19:15:23.714 : T2 finished: true
19:15:25.729 : T1 finished: false
|
线程 T2 立即看到了停止请求。而线程 T1 却始终没有看到:两秒钟之后它仍在运行,直到虚拟机关闭才停止。即时编译器注意到第 7–9 行的循环并不修改 [stop] ,并且没有任何同步要求重新读取它,于是只在循环之前读取了一次这个字段:循环因此变成了死循环。这种行为在这里使用的 HotSpot 虚拟机上是可重现的,但没有保证:另一种虚拟机或另一个版本可能会让 T1 停止。这恰恰就是问题所在:没有 happens-before 关系,程序的行为就是未定义的。
关键字 [volatile] 保证可见性,但不保证 原子性:[value++] 在 [volatile] 字段上仍然是先读后写,两个线程仍然可能丢失一次更新。因此,[volatile] 适用于由一个线程写入、其他线程读取的标志,但不适用于共享计数器。要停止线程,前面介绍的中断实际上比标志更可取:它还能唤醒阻塞在等待中的线程。
8.7.8. 原子类
[java.util.concurrent.atomic] 包(Java 5)提供了一些类,使对变量的简单操作成为 原子的:该操作由线程完整地执行,其他线程不可能在操作中途观察或修改该变量。前面的工具([synchronized]、[ReentrantLock]、[Semaphore])都旨在使一组操作成为原子的,代价是阻塞其他线程。对于简单但频繁的操作,原子类通过使用特殊的处理器指令避免了这种阻塞。[AtomicInteger] 类的主要方法如下:
方法 | 作用 |
[int get()], [void set(int v)] | 读取和写入该值(使用 [volatile] 字段的语义) |
[int incrementAndGet()], [int decrementAndGet()] | 把值加 1(减 1)并返回新值 |
[int getAndIncrement()], [int getAndDecrement()] | 与上面相同,但返回先前的值(类似于 [x++] 和 [x--]) |
[int addAndGet(int delta)] | 把 [delta] 加到该值上并返回新值 |
[int getAndSet(int v)] | 赋值 [v] 并返回旧值 |
[boolean compareAndSet(int expectedValue, int newValue)] | 赋值 [newValue] ,仅当值为 [expectedValue] 时;返回 [true] 表示发生了赋值 |
[int updateAndGet(IntUnaryOperator f)] | 以原子方式把值 v 替换为 f(v),并返回新值 |
该包还提供 [AtomicLong]、[AtomicBoolean]、[AtomicReference<V>] (对对象的原子引用),以及原子数组([AtomicIntegerArray]……)。[LongAdder] 类(Java 8)是为许多线程非常频繁地更新而设计的计数器:它不是让所有线程竞争同一个变量,而是把递增分散到多个单元中,只有在请求求和时([sum])才把它们加在一起。
程序 [Threads17.java] 以程序 [Threads09.java] 的实验为基础,比较了五种使共享计数器递增的方式:
| // 原子类:无锁操作
// 参数:线程数,每个线程的递增次数
int nbThreads;
int nbIncrements;
void main(String[] args) throws InterruptedException {
nbThreads = args.length > 0 ? Integer.parseInt(args[0]) : 4;
nbIncrements = args.length > 1 ? Integer.parseInt(args[1]) : 10_000_000;
IO.println("%d threads, %,d increments per thread, expected value %,d"
.formatted(nbThreads, nbIncrements, nbThreads * nbIncrements));
// 递增共享计数器的五种方式
measure("without synchronization", Counter::withoutSynchronization, () -> Counter.value);
measure("with synchronized", Counter::withSynchronized, () -> Counter.value);
measure("with ReentrantLock", Counter::withReentrantLock, () -> Counter.value);
measure("with AtomicInteger", Counter::withAtomicInteger, Counter.atomic::get);
measure("with LongAdder", Counter::withLongAdder, Counter.adder::sum);
}
// 启动所有执行 [increment] 共 nbIncrements 次的线程,然后显示 [value]
void measure(String method, Runnable increment, LongSupplier value) throws InterruptedException {
Counter.reset();
// 启动信号,使所有线程同时开始
var start = new CountDownLatch(1);
var threads = new Thread[nbThreads];
for (int i = 0; i < nbThreads; i++) {
threads[i] = Thread.ofPlatform().start(() -> {
try {
start.await();
} catch (InterruptedException e) {
return;
}
for (int j = 0; j < nbIncrements; j++) {
increment.run();
}
});
}
// 出发!
long begin = System.nanoTime();
start.countDown();
for (Thread thread : threads) {
thread.join();
}
long duration = (System.nanoTime() - begin) / 1_000_000;
IO.println("%-24s : obtained value %,12d in %5d ms".formatted(method, value.getAsLong(), duration));
}
// 共享资源
static class Counter {
// volatile 保证写入的可见性,而不保证 value++ 的原子性
static volatile int value;
private static final Object lock = new Object();
private static final ReentrantLock reentrantLock = new ReentrantLock();
static final AtomicInteger atomic = new AtomicInteger();
static final LongAdder adder = new LongAdder();
// 将计数器重置为零
static void reset() {
value = 0;
atomic.set(0);
adder.reset();
}
// 读取、递增、写入:非原子操作
static void withoutSynchronization() {
value++;
}
// 由 synchronized 保护的临界区
static void withSynchronized() {
synchronized (lock) {
value++;
}
}
// 由 ReentrantLock 保护的临界区
static void withReentrantLock() {
reentrantLock.lock();
try {
value++;
} finally {
reentrantLock.unlock();
}
}
// 原子递增,无锁
static void withAtomicInteger() {
atomic.incrementAndGet();
}
// 分布式加法器的递增,无锁
static void withLongAdder() {
adder.increment();
}
}
|
说明:
- 第 4–5 行:在紧凑源文件中,字段可以声明在任何类之外;它们是隐式类的字段。实例方法 [main] 和 [measure] 会使用它们;
- 第 14–18 行:方法 [measure] 被传入五种不同的递增方法(作为 [Runnable])和一个返回所得结果的函数来调用,后者的类型为 [LongSupplier](类型为 [long getAsLong()] 的函数式接口)。方法引用 [Counter.atomic::get] 和 [Counter.adder::sum] 指向两个特定对象的方法;
- 第 22–47 行:方法 [measure] 启动 [nbThreads] 个线程,每个线程调用所接收的方法 [nbIncrements] 次,并测量总时间。格式 [%,12d] 把值右对齐到 12 个字符,并带有千位分隔符;
- 第 25、30 和 41 行:所有线程都在一个 [CountDownLatch] 后面等待,它在所有线程都启动之后才打开。因此它们同时开始工作,使并发访问比逐个启动线程时更有可能发生;
- 第 52 行:计数器是 [volatile] 的。这阻止了编译器即时执行我们在 [Threads09.java] 中观察到的那种优化:每次递增都真正地从内存读取并写入内存;
- 第 67 行:不同步的递增;
- 第 72–74 行和第 79–84 行:在由 [synchronized] 或 [ReentrantLock] 保护的临界区内递增;
- 第 89 行:原子递增;
- 第 94 行:对 [LongAdder] 递增。
结果:
| > java Threads17.java
4 threads, 10,000,000 increments per thread, expected value 40,000,000
without synchronization : obtained value 22,447,283 in 729 ms
with synchronized : obtained value 40,000,000 in 3789 ms
with ReentrantLock : obtained value 40,000,000 in 1145 ms
with AtomicInteger : obtained value 40,000,000 in 739 ms
with LongAdder : obtained value 40,000,000 in 293 ms
|
- 没有同步时,结果再次出错:[volatile] 字段并没有使 [value++] 成为原子操作;
- 其他四种方法返回正确的结果;
- 在这次执行中,原子类明显比锁快。锁在这里代价高昂,因为四个线程在一个微小的操作上不断竞争它们。测得的执行时间在很大程度上取决于机器及其负载:只有它们的数量级才有意义。[LongAdder] 最快:它的线程之间的相互干扰比竞争 [AtomicInteger] 中单个变量的线程要少,而且它的性能优势会随着处理器数量的增加而增大。
[compareAndSet] 方法(“CAS”)是“无锁”算法的基本构件:我们读取值,计算新值,然后仅当变量在此期间没有改变时才写入它;否则,就重新开始。[updateAndGet] 做的就是这件事,稍后介绍的并发集合也大量使用它。
8.8. 并发访问多个共享资源
8.8.1. 死锁
在我们前面的示例中,不同的线程共享的是单个资源。如果有多个资源并且它们相互依赖,情况就会变得更复杂。尤其是可能发生死锁:两个线程互相等待。考虑下面依次发生的动作:
- 线程 T1 获取锁 V1,以访问共享资源 R1;
- 线程 T2 获取锁 V2,以访问共享资源 R2;
- 线程 T1 请求锁 V2。它被阻塞;
- 线程 T2 请求锁 V1。它被阻塞。
线程 T1 和 T2 无限期地互相等待。有几种可行的解决方案:
- 使用单个锁同时请求两个资源。如果这会导致对一个代价高昂的资源长时间加锁,这就并不总是可行;
- 始终 按 相同的顺序获取锁:如果所有线程都先获取 V1 再获取 V2,就不可能发生死锁。这是最常用的规则;
- 持有 V1 却无法获取 V2 的线程会释放 V1,以避免死锁。
程序 [Threads18.java] 会造成死锁,并通过使用 [tryLock] 方法(属于 [ReentrantLock])实现最后一种解决方案:
| // 死锁:两个线程以不同的顺序获取两把锁
void main() throws InterruptedException {
// 两个共享资源的锁
var lockR1 = new ReentrantLock();
var lockR2 = new ReentrantLock();
// T1 获取 R1,然后请求 R2;2 秒后放弃
var t1 = new Thread(() -> work(lockR1, "R1", lockR2, "R2", Duration.ofSeconds(2)), "T1");
// T2 获取 R2,然后请求 R1;最多等待 5 秒
var t2 = new Thread(() -> work(lockR2, "R2", lockR1, "R1", Duration.ofSeconds(5)), "T2");
t1.start();
t2.start();
t1.join();
t2.join();
IO.println("End of Main");
}
// 获取第 1 个资源,然后在 [timeout] 内尝试获取第 2 个
static void work(Lock first, String firstName, Lock second, String secondName, Duration timeout) {
String name = Thread.currentThread().getName();
first.lock();
try {
IO.println(time() + " : " + name + " obtained " + firstName);
// 我们给另一个线程留出获取其第一个资源的时间
Thread.sleep(500);
IO.println(time() + " : " + name + " requests " + secondName);
// 带最长等待时间的请求,而不是会无限期等待的 lock()
if (second.tryLock(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
try {
IO.println(time() + " : " + name + " obtained " + secondName
+ " and works with " + firstName + " and " + secondName);
} finally {
second.unlock();
}
} else {
IO.println(time() + " : " + name + " did not obtain " + secondName + " within " + timeout.toSeconds()
+ " s: it releases " + firstName + " and gives up");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
first.unlock();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 5–6 行:两个资源的锁。它们在这里是局部变量,被第 9 行和第 11 行的 lambda 捕获;
- 第 9 行:线程 T1 获取 R1,然后请求 R2;它最多等待 2 秒;
- 第 11 行:线程 T2 获取 R2,然后请求 R1——也就是说,顺序相反;它最多等待 5 秒;
- 第 20 行:方法 [work] 获取由接口 [Lock] 所定义类型的锁,该接口由 [ReentrantLock] 实现;
- 第 22 行:线程获取它的第一个资源。第 42 行的 [finally] 子句无论如何都会释放它;
- 第 26 行:它等待半秒钟,让另一个线程有时间获取它自己的第一个资源:此时死锁就是必然的;
- 第 29 行:线程不使用会无限期等待的 [lock],而是以最长等待时间请求第二个锁。[tryLock] 在获得锁时返回 [true] ,在超时到期时返回 [false] 。超时用一个数字和一个单位来表示([TimeUnit.MILLISECONDS]);方法 [toMillis()] 把时长 [timeout] 转换为毫秒;
- 第 34 行:通过 [tryLock] 获取的锁必须通过 [unlock] 释放,并放在 [finally] 子句中;
- 第 36–39 行:如果未能获取第二个锁,线程就中止。退出方法时,它会释放它的第一个资源(第 43 行);
- 第 40–41 行:[sleep] 和带超时的 [tryLock], 都可能抛出 [InterruptedException]。
结果:
| > java Threads18.java
19:15:36.043 : T1 obtained R1
19:15:36.033 : T2 obtained R2
19:15:36.553 : T2 requests R1
19:15:36.554 : T1 requests R2
19:15:38.554 : T1 did not obtain R2 within 2 s: it releases R1 and gives up
19:15:38.558 : T2 obtained R1 and works with R2 and R1
End of Main
|
两个线程各自获得了它们的第一个资源,然后请求第二个:它们发生了死锁。2 秒之后,T1 放弃并释放 R1;仍在等待的 T2 立即获得 R1,并可以执行它的工作。如果没有超时,程序永远不会结束。这一系列事件是可重现的;只有第 2 行和第 3 行的顺序以及第 4 行和第 5 行的顺序可能改变。使用 [synchronized] 代码块无法编写这个程序,因为它们的等待时间无法限制。
当 Java 程序似乎被冻结时,JDK 的 [jcmd <pid> Thread.print] 命令会显示它每个线程的调用栈([pid] 是进程 ID,不带任何参数运行 [jcmd] 命令即可得到);它会检测锁之间的死锁,并用消息“Found one Java-level deadlock”报告它们,随后列出所涉及的线程和锁。
8.8.2. 示例:读者与写者
考虑下面的示例:
- 我们有一个数组,一些线程向其中写入数据(写者),另一些线程读取数据(读者);
- 写者彼此平等但互斥:一次只有一个写者可以向数组写入数据;
- 读者彼此平等但互斥:一次只有一个读者可以读取数组中存储的数据;
- 只有当写者在数组中放入了一些数据时,读者才能从数组中读取数据;只有当数组中已有的数据被读者读取之后,写者才能向数组中放入新的数据。
有两种类型的共享资源:
- 可写的表:一次只有一个写者可以访问它;
- 只读的表:一次只有一个读者可以访问它。
以及使用这些资源的顺序:
- 读者必须总是跟在写者之后;
- 写者必须总是跟在读者之后,第一次除外。
可以使用两个 [Semaphore] 类型的屏障来控制对这两个资源的访问:
- [canWrite] 屏障控制写者对数组的访问;
- 屏障 [canRead] 控制读者对数组的访问;
- [canWrite] 屏障以打开状态创建(一个许可),允许第一个写者通过,并阻塞所有其他写者;
- [canRead] 屏障以关闭状态创建(没有许可),阻塞所有读者;
- 当写者完成工作后,它打开屏障 [canRead] ,让一个读者进入;
- 当读者完成工作后,它打开屏障 [canWrite] ,让一个写者进入。
在这里我们看到了不属于任何线程的屏障的好处:屏障 [canRead] 由读者关闭(取走许可),由写者打开(归还许可)。这对于锁是不可能的,因为锁只能由持有它的线程释放。演示这种同步的程序 [Threads19.java] 如下:
| // 由两个信号量同步的读者和写者
void main() {
// 每种线程的数量
final int nbThreads = 2;
// 创建并启动读者线程
for (int i = 0; i < nbThreads; i++) {
new Thread(Board::read, "R" + i).start();
}
// 创建并启动写者线程
for (int i = 0; i < nbThreads; i++) {
new Thread(Board::write, "W" + i).start();
}
// main 结束:其他线程继续工作
IO.println("End of Main...");
}
// 共享资源及其同步
static class Board {
// 读者与写者之间共享的数组
private static final int[] data = new int[3];
// 表示可以读取 data 的内容:开始时关闭(没有许可)
private static final Semaphore canRead = new Semaphore(0);
// 表示可以写入 data:开始时打开(有一个许可)
private static final Semaphore canWrite = new Semaphore(1);
// 读取数组的内容
static void read() {
String name = Thread.currentThread().getName();
IO.println("Method [read] started by thread " + name);
// 我们等待读取许可
canRead.acquireUninterruptibly();
// 读取数组
for (int i = 0; i < data.length; i++) {
// 等待 0.5 秒:线程让出处理器
sleep(500);
IO.println(time() + " : reader " + name + " read the number " + data[i]);
}
// 我们允许一个写者
canWrite.release();
IO.println("Method [read] finished by thread " + name);
}
// 写入数组
static void write() {
String name = Thread.currentThread().getName();
IO.println("Method [write] started by thread " + name);
// 我们等待写入许可
canWrite.acquireUninterruptibly();
// 写入数组
for (int i = 0; i < data.length; i++) {
// 等待 0.5 秒
sleep(500);
// ThreadLocalRandom:每个线程专用的随机数生成器
data[i] = ThreadLocalRandom.current().nextInt(0, 1000);
IO.println(time() + " : writer " + name + " wrote the number " + data[i]);
}
// 我们允许一个读者
canRead.release();
IO.println("Method [write] finished by thread " + name);
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 8–14 行:创建并启动两个读者线程,然后是两个写者线程。没有保留对这些线程的引用:主线程不等待它们;
- 第 16 行:主线程立即终止。进程会一直持续到所有四个线程(它们不是守护线程)结束;
- 第 22 行:数组 [data] 是读者线程和写者线程之间的共享资源;
- 第 24 行:屏障 [canRead] 向读者发出信号,表明它们可以读取数组。它由填充了数组的写者打开。它以关闭状态创建:必须先由一个写者填充数组;
- 第 26 行:屏障 [canWrite] 通知写者它们可以向数组写入。它由读完整个数组的读者打开。它以打开状态创建:数组从一开始就是可写的;
- 第 33 行:读者等待写者发出数组已被填充的信号。当这个信号到来时,只有一个等待中的读者继续;
- 第 35–39 行:读取数组,每读一个元素暂停半秒钟,以迫使线程让出 CPU;
- 第 41 行:读者通知写者,数组已被读取,可以再次填充;
- 方法 [write] 与方法 [read] 是对称的;
- 第 56 行:写入的数字是随机生成的。[ThreadLocalRandom.current()] 方法(Java 7)返回当前线程专用的随机数生成器:线程之间不会竞争同一个生成器。[nextInt(0, 1000)] 方法返回区间 [0, 1000[ 内的一个整数;
- 数组 [data] 没有受到任何锁的保护。然而,这里没有数据竞争:写者的写入先于它的 [canRead.release()],而后者先于(happens-before 关系)读者的 [canRead.acquireUninterruptibly()],因而也先于它的读取。
结果:
| > java Threads19.java
Method [read] started by thread R0
Method [read] started by thread R1
Method [write] started by thread W0
End of Main...
Method [write] started by thread W1
19:15:41.498 : writer W0 wrote the number 408
19:15:42.004 : writer W0 wrote the number 58
19:15:42.505 : writer W0 wrote the number 490
Method [write] finished by thread W0
19:15:43.006 : reader R0 read the number 408
19:15:43.507 : reader R0 read the number 58
19:15:44.016 : reader R0 read the number 490
Method [read] finished by thread R0
19:15:44.520 : writer W1 wrote the number 310
19:15:45.020 : writer W1 wrote the number 964
19:15:45.520 : writer W1 wrote the number 830
Method [write] finished by thread W1
19:15:46.021 : reader R1 read the number 310
19:15:46.521 : reader R1 read the number 964
19:15:47.022 : reader R1 read the number 830
Method [read] finished by thread R1
|
可以注意到以下几点:
- 一次只有一个读者,尽管它在临界区 [read] 中会失去 CPU;
- 一次只有一个写者,尽管它在临界区 [write] 中会失去处理器;
- 只有当数组中有内容可读时,读者才会读取;
- 只有当数组已被完全读完时,写者才会写入;
- 另一方面,我们无法控制它们出现的顺序:没有理由要求写者 W0 先于写者 W1,也没有理由要求读者 R0 先于读者 R1。再次执行可能会得到不同的顺序。
8.8.3. wait 和 notifyAll 方法
在前面的示例中,当写者阻塞在指令 [canWrite.acquireUninterruptibly()] 上时,其中一个——任意一个——会被操作 [canWrite.release()] 解除阻塞。如果想为某个特定的写者打开屏障,事情就变得更复杂了。
考虑一个有服务柜台的公共服务办事处的类比。顾客到达时,从取号机上取一张编号的号码票,然后去坐下。通过扬声器按号码叫顾客。等待期间,顾客可以做任何他们想做的事:可以看书,也可以打瞌睡。每当扬声器播报一个号码,他们就会被唤醒。如果是他们的号码,顾客就起身走向柜台;否则,他们就回去继续做原来的事。我们可以用类似的方式来处理线程。我们以写者为例:
在柜台 | 对于线程 |
几位写者在等待同一个柜台 | 它们的线程被阻塞 |
柜台变得可用,并叫到下一位写者的号码 | 从数组中读取数据的线程通知写者数组可用了。由该线程或另一个线程判定应由哪一个写者继续 |
每位写者核对自己的号码;只有号码被叫到的那一位前往柜台;其余的回到等待队列 | 每个线程检查自己是否是被选中的那一个。如果是,它就通过屏障;否则,它回到等待队列 |
Java 允许您使用 每个对象都具备的方法来实现这个场景,因为这些方法定义在 [Object] 类中:
方法 | 作用 |
[void wait()] | 归还对象的监视器,并阻塞线程,直到另一个线程通过 [notify] 或 [notifyAll] 发出变更信号;线程随后必须重新取回监视器才能继续。等待可以被中断([InterruptedException]) |
[void wait(long ms)] | 与上面相同,但带有最长等待时间 |
[void notify()] | 唤醒在此对象上因 [wait] 而阻塞的线程之一 |
[void notifyAll()] | 唤醒在此对象上因 [wait] 而阻塞的所有线程 |
我们现在来描述一种标准模式——尤其是 Brian Goetz 等人的著作 [Java Concurrency in Practice] 中介绍过的——它可以解决带有进入条件的屏障问题。
共享资源(柜台)的线程通过一个我们称为 令牌的对象来访问它:它是一个简单的对象([new Object()]),使用的是它的监视器。要穿过通往柜台的屏障,必须持有令牌,而令牌只有一个。因此,线程必须来回传递令牌。
要前往柜台,线程首先使用 [synchronized (token)] 代码块请求令牌。如果它获得了令牌,就在循环 [while (!iAmTheExpectedOne) { token.wait(); }] 中检查自己是否满足前往柜台的条件,然后仍在 [synchronized] 代码块内前往柜台。如果该线程不是柜台所期待的那一个,它就通过 [token.wait()] 归还令牌,让出它的轮次,并进入阻塞状态。当另一个线程发出访问条件变更的信号时,它会被唤醒;随后它会取回令牌并再次检查条件。这就是为什么测试是循环([while]) 而不是简单的 [if]。还有第二个原因,是 Java 特有的:规范允许出现“虚假唤醒”,即 [wait] 在没有任何线程调用 [notify] 的情况下结束;循环使这些虚假唤醒变得无害。操作 [token.wait()] 只能由持有令牌监视器的线程执行;否则会抛出 [IllegalMonitorStateException] 异常。在这种方案中,令牌只有在事务完成之后才会被释放。
修改柜台访问条件的线程也必须持有令牌并通知等待中的线程:在 [synchronized (token)] 代码块内,它修改柜台的访问条件,然后使用 [token.notifyAll()] 唤醒等待中的线程。
唤醒线程意味着等待中的线程成为令牌的候选者;它们不会立即得到令牌。令牌只有在 [synchronized] 代码块结束时才可用。随后,所有被唤醒的线程会依次、以不确定的顺序得到令牌,这让它们有机会再次检查访问条件。第一个满足条件的线程保留令牌,并前往队列。
有了这些信息,我们就可以重写读者/写者应用程序,指定读者和写者前往各自柜台的顺序([Threads20.java]):
| // 读者和写者按规定顺序访问计数器:wait / notifyAll
void main() {
// 每种线程的数量
final int nbThreads = 3;
// 读者的顺序:与创建顺序相反
Board.readOrder = IntStream.range(0, nbThreads).mapToObj(i -> "R" + (nbThreads - 1 - i)).toList();
// 写者的顺序:创建顺序
Board.writeOrder = IntStream.range(0, nbThreads).mapToObj(i -> "W" + i).toList();
for (int i = 0; i < nbThreads; i++) {
IO.println("Reader " + Board.readOrder.get(i) + " is in position " + i
+ ", writer " + Board.writeOrder.get(i) + " is in position " + i);
}
// 先创建并启动读者线程,再创建并启动写者线程
for (int i = 0; i < nbThreads; i++) {
new Thread(Board::read, "R" + i).start();
}
for (int i = 0; i < nbThreads; i++) {
new Thread(Board::write, "W" + i).start();
}
// 写入授权
Board.allowWriting();
// main 结束
IO.println("End of Main...");
}
// 共享资源及其同步
static class Board {
// 读者与写者之间共享的数组
private static final int[] data = new int[3];
// 读计数器和写计数器的访问令牌
private static final Object canRead = new Object();
private static final Object canWrite = new Object();
// 计数器的访问条件
private static boolean readingAllowed = false;
private static boolean writingAllowed = false;
private static int nextReader = 0;
private static int nextWriter = 0;
// 读者和写者的顺序
static List<String> readOrder = List.of();
static List<String> writeOrder = List.of();
// 打开写计数器
static void allowWriting() {
synchronized (canWrite) {
writingAllowed = true;
// 我们唤醒所有等待令牌的写者
canWrite.notifyAll();
}
}
// 读取数组的内容
static void read() {
String name = Thread.currentThread().getName();
IO.println("Method [read] started by thread " + name);
// 我们请求读计数器的令牌
synchronized (canRead) {
try {
// 只要还没轮到我们,就归还令牌并等待
while (!readingAllowed || !readOrder.get(nextReader).equals(name)) {
canRead.wait();
}
} catch (InterruptedException e) {
return;
}
// 在计数器处:读取数组
for (int i = 0; i < data.length; i++) {
sleep(500);
IO.println(time() + " : reader " + name + " read the number " + data[i]);
}
// 下一个读者
readingAllowed = false;
nextReader++;
// 我们通知写者可以写入了
synchronized (canWrite) {
writingAllowed = true;
canWrite.notifyAll();
}
IO.println("Method [read] finished by thread " + name);
}
}
// 写入数组
static void write() {
String name = Thread.currentThread().getName();
IO.println("Method [write] started by thread " + name);
// 我们请求写计数器的令牌
synchronized (canWrite) {
try {
// 只要还没轮到我们,就归还令牌并等待
while (!writingAllowed || !writeOrder.get(nextWriter).equals(name)) {
canWrite.wait();
}
} catch (InterruptedException e) {
return;
}
// 在计数器处:写入数组
for (int i = 0; i < data.length; i++) {
sleep(500);
data[i] = ThreadLocalRandom.current().nextInt(0, 1000);
IO.println(time() + " : writer " + name + " wrote the number " + data[i]);
}
// 下一个写者
writingAllowed = false;
nextWriter++;
// 我们通知读者可以读取了
synchronized (canRead) {
readingAllowed = true;
canRead.notifyAll();
}
IO.println("Method [write] finished by thread " + name);
}
}
}
|
读柜台的访问由以下内容决定:
- 第 35 行:令牌 [canRead];
- 第 38 行:布尔值 [readingAllowed];
- 第 43 行:读者姓名的有序列表。读者按此处列出的顺序前往读取台;
- 第 40 行:[nextReader] 是该列表中下一个获准前往柜台的读者的索引。
写柜台的访问同样由令牌 [canWrite]、布尔值 [writingAllowed]、列表 [writeOrder] 和索引 [nextWriter] 控制。
主程序:
- 第 8–10 行:读者按创建顺序的逆序(R2、R1、R0)前往柜台,写者按创建顺序(W0、W1、W2)前往。这些列表通过管道构造:[IntStream.range(0, nbThreads)] 生成整数 0、1、2;[mapToObj] 将每个整数转换为线程名;[toList()] (Java 16)将这些名称收集到一个只读列表中;
- 第 17–22 行:先创建并启动读者,再创建并启动写者。由于既不允许读也不允许写,它们都将被阻塞;
- 第 25 行:允许写入,并通知写者状态已发生变化(方法 [allowWriting],第 47–53 行)。
[read] 方法:
- 第 60–83 行:读取台的整个处理过程由对令牌 [synchronized] [canRead] 的块控制。获得令牌的读者在整个停留期间都持有它;
- 第 63–65 行:获得令牌的读者,如果不允许读取或尚未轮到它,就归还令牌。姓名通过 [equals] 比较;
- 第 66–68 行:如果线程在等待期间被中断,则中止;
- 第 70–73 行:在柜台的处理(读取表);
- 第 75–76 行:读者修改读队列的访问条件。它仍持有读令牌,这些修改会阻止任何读者继续前进;
- 第 78–81 行:读者修改写队列的访问条件,并通知所有等待的写者状态已发生变化。为此,它获取令牌 [canWrite]:这里可以看到该线程同时持有两个令牌。写者以相反的顺序做同样的事(它们持有 [canWrite] 并请求 [canRead]),这正是上文所述的死锁情形。不过这里没有风险:线程只在访问柜台结束时才请求第二个令牌,两个柜台绝不会同时被占用,而其他线程持有令牌的时间仅够检查访问条件,并不会请求另一个令牌。
方法 [write] 与方法 [read] 是对称的。请注意这里使用的是 [notifyAll] 而不是 [notify](后者只唤醒单个线程):如果该线程不是预期的写者,它会重新进入休眠,而预期的写者可能永远不会被唤醒。当访问条件指定了某个特定线程时,必须使用 [notifyAll]。
下面是一次执行的示例:
| > java Threads20.java
Reader R2 is in position 0, writer W0 is in position 0
Reader R1 is in position 1, writer W1 is in position 1
Reader R0 is in position 2, writer W2 is in position 2
Method [write] started by thread W0
Method [read] started by thread R0
Method [read] started by thread R1
Method [read] started by thread R2
End of Main...
Method [write] started by thread W1
Method [write] started by thread W2
19:15:51.612 : writer W0 wrote the number 641
19:15:52.152 : writer W0 wrote the number 32
19:15:52.653 : writer W0 wrote the number 386
Method [write] finished by thread W0
19:15:53.186 : reader R2 read the number 641
19:15:53.687 : reader R2 read the number 32
19:15:54.187 : reader R2 read the number 386
Method [read] finished by thread R2
19:15:54.688 : writer W1 wrote the number 213
19:15:55.188 : writer W1 wrote the number 694
19:15:55.696 : writer W1 wrote the number 502
Method [write] finished by thread W1
19:15:56.200 : reader R1 read the number 213
19:15:56.716 : reader R1 read the number 694
19:15:57.216 : reader R1 read the number 502
Method [read] finished by thread R1
19:15:57.719 : writer W2 wrote the number 102
19:15:58.224 : writer W2 wrote the number 163
19:15:58.732 : writer W2 wrote the number 249
Method [write] finished by thread W2
19:15:59.274 : reader R0 read the number 102
19:15:59.775 : reader R0 read the number 163
19:16:00.275 : reader R0 read the number 249
Method [read] finished by thread R0
|
写者和读者在各自的柜台轮流访问,各自遵循指定的顺序:W0、R2、W1、R1、W2、R0。与前一个程序不同,这个通过顺序是可重现的;每次执行之间只有“已启动”消息的顺序会变化。
8.8.4. 条件:Condition 接口
方法 [wait] 和 [notifyAll] 与对象的监视器相关联,因而与 [synchronized] 块相关联。对于锁 [ReentrantLock],对应的是接口 [java.util.concurrent.locks.Condition]:[Condition] 对象由锁的 [newCondition()] 方法创建,并提供方法 [await()] (相当于 [wait])、[await(long time, TimeUnit unit)]、[signal()] (相当于 [notify])和 [signalAll()] (相当于 [notifyAll])。它们的使用规则相同:线程必须持有锁,并且在 [while] 循环中测试访问条件。
关键优势在于,一个锁可以有多个条件,也就是多个相互独立的队列。在我们的问题中,一个锁就可以保护两个柜台,读者和写者各有一个条件:读完的读者唤醒写者,并且只唤醒写者。不再有两个令牌,因此也就不再需要留意锁的嵌套。程序 [Threads21.java] 的主程序与 [Threads20.java] 相同;其类 [Board] 如下:
| // 共享资源及其同步
static class Board {
// 读者与写者之间共享的数组
private static final int[] data = new int[3];
// 两个计数器共用一把锁
private static final ReentrantLock lock = new ReentrantLock();
// 与这把锁关联的两个条件:两个不同的等待队列
private static final Condition canRead = lock.newCondition();
private static final Condition canWrite = lock.newCondition();
// 计数器的访问条件
private static boolean readingAllowed = false;
private static boolean writingAllowed = false;
private static int nextReader = 0;
private static int nextWriter = 0;
// 读者和写者的顺序
static List<String> readOrder = List.of();
static List<String> writeOrder = List.of();
// 打开写计数器
static void allowWriting() {
lock.lock();
try {
writingAllowed = true;
// 我们唤醒所有写者,且只唤醒写者
canWrite.signalAll();
} finally {
lock.unlock();
}
}
// 读取数组的内容
static void read() {
String name = Thread.currentThread().getName();
IO.println("Method [read] started by thread " + name);
lock.lock();
try {
// 只要还没轮到我们,就归还锁并等待信号
while (!readingAllowed || !readOrder.get(nextReader).equals(name)) {
canRead.await();
}
// 在计数器处:读取数组
for (int i = 0; i < data.length; i++) {
sleep(500);
IO.println(time() + " : reader " + name + " read the number " + data[i]);
}
// 下一个读者
readingAllowed = false;
nextReader++;
// 我们通知写者可以写入了
writingAllowed = true;
canWrite.signalAll();
IO.println("Method [read] finished by thread " + name);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
// 写入数组
static void write() {
String name = Thread.currentThread().getName();
IO.println("Method [write] started by thread " + name);
lock.lock();
try {
// 只要还没轮到我们,就归还锁并等待信号
while (!writingAllowed || !writeOrder.get(nextWriter).equals(name)) {
canWrite.await();
}
// 在计数器处:写入数组
for (int i = 0; i < data.length; i++) {
sleep(500);
data[i] = ThreadLocalRandom.current().nextInt(0, 1000);
IO.println(time() + " : writer " + name + " wrote the number " + data[i]);
}
// 下一个写者
writingAllowed = false;
nextWriter++;
// 我们通知读者可以读取了
readingAllowed = true;
canRead.signalAll();
IO.println("Method [write] finished by thread " + name);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
}
|
说明:
- 第 35 行:一个单一的非公平锁;
- 第 37–38 行:由该锁创建的两个条件;
- 第 49–58 行:为了打开写通道,先获取锁,修改访问条件,然后通过 [canWrite.signalAll()] 唤醒写者;
- 第 64–86 行:切换到读通道是在持有锁的情况下完成的,遵循 [lock] / [try] / [finally] / [unlock] 的顺序;
- 第 67–69 行:在轮到自己之前,读者在条件 [canRead] 上等待。方法 [await] 在等待期间释放锁,并在交还控制权之前重新获取锁;
- 第 79–80 行:读者授权写入并唤醒写者。它已经持有锁,因此不需要获取第二个令牌;
- 第 82–83 行:如果线程在等待期间被中断,它会重置其中断标志并终止;[finally] 子句负责释放锁。
结果:
| > java Threads21.java
Reader R2 is in position 0, writer W0 is in position 0
Reader R1 is in position 1, writer W1 is in position 1
Reader R0 is in position 2, writer W2 is in position 2
Method [read] started by thread R0
Method [read] started by thread R1
Method [read] started by thread R2
Method [write] started by thread W1
Method [write] started by thread W0
End of Main...
Method [write] started by thread W2
19:16:04.039 : writer W0 wrote the number 735
19:16:04.610 : writer W0 wrote the number 678
19:16:05.120 : writer W0 wrote the number 594
Method [write] finished by thread W0
19:16:05.621 : reader R2 read the number 735
19:16:06.158 : reader R2 read the number 678
19:16:06.660 : reader R2 read the number 594
Method [read] finished by thread R2
19:16:07.167 : writer W1 wrote the number 976
19:16:07.667 : writer W1 wrote the number 84
19:16:08.167 : writer W1 wrote the number 970
Method [write] finished by thread W1
19:16:08.671 : reader R1 read the number 976
19:16:09.172 : reader R1 read the number 84
19:16:09.672 : reader R1 read the number 970
Method [read] finished by thread R1
19:16:10.173 : writer W2 wrote the number 54
19:16:10.673 : writer W2 wrote the number 7
19:16:11.174 : writer W2 wrote the number 323
Method [write] finished by thread W2
19:16:11.676 : reader R0 read the number 54
19:16:12.188 : reader R0 read the number 7
19:16:12.700 : reader R0 read the number 323
Method [read] finished by thread R0
|
其行为与前一个程序相同:W0、R2、W1、R1、W2、R0。
8.8.5. 多个读者同时读取:ReadWriteLock
在前面的示例中,读者是互斥的。在许多应用中,这种限制是不必要的:在没有人修改数据的同时,多个线程可以一起读取数据。只有写入必须是互斥的:当写者正在修改数据时,任何读者或其他写者都不应访问它。这就是经典的读写问题,可以通过 [java.util.concurrent.locks.ReadWriteLock] 接口来解决。[ReadWriteLock] 对象提供两个相互关联的锁:
- [readLock()]:读锁,只要没有线程持有写锁,就可以被多个线程同时持有;
- [writeLock()]:写锁,是互斥的。
程序 [Threads22.java] 如下:
| // 多个读者同时读取,单个写者:ReadWriteLock
void main() throws InterruptedException {
var catalog = new Catalog();
var threads = new ArrayList<Thread>();
// 三个读者两次查询键盘的价格
for (int i = 0; i < 3; i++) {
threads.add(Thread.ofPlatform().name("R" + i).start(() -> {
catalog.read("keyboard");
catalog.read("keyboard");
}));
}
// 一个 0.5 秒后启动的写者修改这个价格
Thread.sleep(500);
threads.add(Thread.ofPlatform().name("W").start(() -> catalog.modify("keyboard", 25)));
// 等待所有线程结束
for (Thread thread : threads) {
thread.join();
}
}
// 共享资源:价格目录
static class Catalog {
private final Map<String, Integer> prices = new HashMap<>(Map.of("keyboard", 20, "mouse", 10));
// 一把读者用的锁,一把写者用的锁
private final ReadWriteLock lock = new ReentrantReadWriteLock();
// 多个线程可以同时持有读锁
int read(String article) {
String name = Thread.currentThread().getName();
lock.readLock().lock();
try {
IO.println(time() + " : " + name + " starts reading the price of " + article);
// 长时间读取
sleep(1000);
int p = prices.get(article);
IO.println(time() + " : " + name + " read the price of " + article + " : " + p);
return p;
} finally {
lock.readLock().unlock();
}
}
// 写锁是独占的:没有读者,也没有其他写者
void modify(String article, int newPrice) {
String name = Thread.currentThread().getName();
IO.println(time() + " : " + name + " requests the write lock");
lock.writeLock().lock();
try {
IO.println(time() + " : " + name + " starts modifying the price of " + article);
// 长时间写入
sleep(1000);
prices.put(article, newPrice);
IO.println(time() + " : " + name + " set the price of " + article + " to " + newPrice);
} finally {
lock.writeLock().unlock();
}
}
}
|
说明:
- 第 23–59 行:共享资源是一个价格目录,存储在名为 [HashMap] 的字典中(第 24 行);
- 第 26 行:[ReentrantReadWriteLock] 是 [ReadWriteLock] 接口的实现;
- 第 29–42 行:方法 [read] 为一次持续一秒的读操作获取读锁;
- 第 45–58 行:[modify] 方法在持续一秒的修改期间获取写锁;
- 第 7–12 行:三个读者连续两次读取键盘的价格;
- 第 14–15 行:一个写者在半秒后启动,修改该价格。
结果:
| > java Threads22.java
19:16:15.988 : R2 starts reading the price of keyboard
19:16:16.000 : R1 starts reading the price of keyboard
19:16:15.984 : R0 starts reading the price of keyboard
19:16:16.461 : W requests the write lock
19:16:17.000 : R1 read the price of keyboard : 20
19:16:16.997 : R2 read the price of keyboard : 20
19:16:17.008 : R0 read the price of keyboard : 20
19:16:17.008 : W starts modifying the price of keyboard
19:16:18.008 : W set the price of keyboard to 25
19:16:18.009 : R0 starts reading the price of keyboard
19:16:18.009 : R2 starts reading the price of keyboard
19:16:18.009 : R1 starts reading the price of keyboard
19:16:19.010 : R2 read the price of keyboard : 25
19:16:19.010 : R1 read the price of keyboard : 25
19:16:19.011 : R0 read the price of keyboard : 25
|
- 三个读者同时读取(第 2–4 行和第 6–8 行):如果使用标准锁,第一轮读取将需要三秒而不是一秒;
- 写者在读取进行期间到达,等待它们结束。然后它独自修改了价格;
- 第二轮读取是在写者到达之后才开始的,它等待修改完成,然后读取到新的价格。因此,锁 [ReentrantReadWriteLock] 可以防止源源不断的读者无限期地阻塞写者的写入:在写者等待期间到达的读者排在写者之后。这一顺序是可重现的。
只有在读取很多且足够耗时的情况下,读写锁才有用。对于非常短的读取,[StampedLock] 类(Java 8)提供了一种不加锁的“乐观”读取,事后再进行验证。而对于读取非常频繁、修改很少的集合,下一段介绍的并发集合通常是最佳方案。
8.9. 并发集合
前面的示例保护的都是非常简单的共享数据(一个计数器、一个数组、一个小字典)。当线程共享集合(列表、字典、队列)时,可以用锁保护每一次访问。然而,标准集合([ArrayList]、[HashMap]、[ArrayDeque])在设计上并不支持被多个线程同时修改:不加保护地使用可能导致元素丢失、引发意外的异常([ConcurrentModificationException]),甚至破坏集合的内部结构。方法 [Collections.synchronizedList(…)]、[Collections.synchronizedMap(…)]…… 将普通集合包装成一个每个方法都是 [synchronized] 的对象:这是安全的,但所有线程都要竞争同一个锁,而且遍历集合时仍然必须手动加以保护。自 Java 5 起,[java.util.concurrent] 包提供了专为在线程间共享而设计、无需显式加锁的集合:
集合 | 作用 |
[ConcurrentHashMap<K,V>] | 一种字典,其操作(包括条件更新([merge]、[compute]、[putIfAbsent]……))都是安全且原子的。多个线程可以同时读取和修改它 |
[ConcurrentSkipListMap<K,V>] | 按键排序的字典 |
[CopyOnWriteArrayList<E>] | 每次修改时都会复制其内部数组的列表:读取和遍历速度非常快,且永远不会受到修改的影响。适用于读取频繁、修改很少的列表(例如播放列表) |
[ConcurrentLinkedQueue<E>]、[ConcurrentLinkedDeque<E>] | 队列(先进先出)、双端队列 |
[BlockingQueue<E>] | 一种队列接口:队列为空时阻塞消费者,如果容量有限,则在队列已满时阻塞生产者。实现类有:[ArrayBlockingQueue]、[LinkedBlockingQueue]、[PriorityBlockingQueue]、[SynchronousQueue]…… |
8.9.1. ConcurrentHashMap 和 CopyOnWriteArrayList
在程序 [Threads23.java] 中,四个线程生成随机数,并在一个共享字典中统计每个数出现的次数:
| // 并发集合:ConcurrentHashMap 和 CopyOnWriteArrayList
void main() throws InterruptedException {
// 共享字典:数字 -> 抽取次数
var draws = new ConcurrentHashMap<Integer, Integer>();
// 各线程报告的共享列表
var reports = new CopyOnWriteArrayList<String>();
// 4 个线程各自随机抽取 100,000 个数字
final int nbDraws = 100_000;
var threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = Thread.ofPlatform().name("T" + i).start(() -> {
for (int j = 0; j < nbDraws; j++) {
int digit = ThreadLocalRandom.current().nextInt(0, 10);
// 以值 1 添加该键,或原子地更新已有的值
draws.merge(digit, 1, Integer::sum);
}
// 报告已添加到列表
reports.add("thread %s finished its %,d draws"
.formatted(Thread.currentThread().getName(), nbDraws));
});
}
for (Thread thread : threads) {
thread.join();
}
// 报告,按到达顺序
for (String report : reports) {
IO.println(report);
}
// 抽取结果,按键的顺序
new TreeMap<>(draws).forEach((digit, count) ->
IO.println("digit %d : %,6d draws".formatted(digit, count)));
int total = draws.values().stream().mapToInt(Integer::intValue).sum();
IO.println("total: %,d draws (expected: %,d)".formatted(total, threads.length * nbDraws));
// computeIfAbsent:返回与键关联的值,必要时先计算并添加
IO.println("computeIfAbsent(10, …) = " + draws.computeIfAbsent(10, key -> 0)
+ ", number of keys: " + draws.size());
}
|
说明:
- 第 5 行:共享字典将每个数字与其出现次数关联起来;
- 第 7 行:一个列表,每个线程在工作结束时把一份报告存入其中;
- 第 17 行:方法 [merge(key, value, function)] 在键 [digit] 不存在时添加它并赋值 1,否则将其值 v 替换为 [function(v, 1)],这里就是求和 [Integer::sum]。在 [ConcurrentHashMap] 中,该操作是原子的。我们不能写成 [draws.put(digit, draws.get(digit) + 1)]:这个表达式先读取值再写入新值,分两步操作,两个线程可能会像示例 [Threads09.java] 中那样丢失一次更新;
- 第 20 行:每个线程把自己的报告添加到列表中;
- 第 29–31 行:主线程遍历该列表。对 [CopyOnWriteArrayList] 的遍历是在内部数组的快照上进行的:即使其他线程在遍历期间修改列表,它也绝不会抛出 [ConcurrentModificationException];
- 第 33–34 行:字典被复制到有序字典 [TreeMap] 中,以便按顺序显示数字;方法 [forEach] 接收每个键/值对;
- 第 35 行:由流计算得到的值之和;
- 第 38 行:方法
[computeIfAbsent(key, function)] 返回与键关联的值;如果键不存在,则先用该函数计算出值并添加。与 [merge] 一样,检查和添加构成一个单一的原子操作:先用 [containsKey] 检查再 [put] 是不安全的,因为另一个线程可能在两者之间添加该键。
结果:
| > java Threads23.java
thread T1 finished its 100,000 draws
thread T0 finished its 100,000 draws
thread T2 finished its 100,000 draws
thread T3 finished its 100,000 draws
digit 0 : 40,244 draws
digit 1 : 40,093 draws
digit 2 : 39,719 draws
digit 3 : 40,052 draws
digit 4 : 39,911 draws
digit 5 : 39,687 draws
digit 6 : 39,959 draws
digit 7 : 39,814 draws
digit 8 : 40,235 draws
digit 9 : 40,286 draws
total: 400,000 draws (expected: 400,000)
computeIfAbsent(10, …) = 0, number of keys: 11
|
抽取的总次数是正确的:没有丢失任何更新。报告按线程完成工作的顺序出现,每次执行都可能不同。
8.9.2. 一个生产者和多个消费者:BlockingQueue
读者和写者问题是经典生产者-消费者问题的一个变体:一些线程生产数据,另一些线程消费数据。[BlockingQueue<E>] 接口无需任何显式的同步工具即可解决这个问题:
- [put(element)] 向队列添加一个元素。如果队列容量有限且已满,生产者将被阻塞,直到出现空位;
- [take()] 移除队首的元素。如果队列为空,消费者将被阻塞,直到有元素到来;
- [offer(element, timeout, unit)] 和 [poll(timeout, unit)] 的作用相同,但有最长等待时间;[offer(element)] 和 [poll()] 没有超时设置,从不阻塞:失败时它们返回 [false] 或 [null] 。
队列并不知道生产已经结束。一种经典技术是在生产结束时向队列中放入一个特殊值(英语世界称之为“poison pill”,即“毒丸”),取到它的消费者就知道必须停止。另一种技术是中断消费者,因为 [take] 是可中断的。程序 [Threads24.java] 如下:
| // 使用 BlockingQueue 的生产者 / 消费者
// 表示生产结束的值(“毒丸”)
static final int END = -1;
void main() throws InterruptedException {
// 最多容纳 3 个元素的队列
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
final int nbConsumers = 2;
// 生产者放入 8 个数字,然后表示已完成
var producer = new Thread(() -> {
try {
for (int i = 1; i <= 8; i++) {
// 如果队列已满则阻塞
queue.put(i);
IO.println(time() + " : P put " + i
+ " (waiting elements: " + queue.size() + ")");
Thread.sleep(100);
}
// 每个消费者一个结束标记
for (int i = 0; i < nbConsumers; i++) {
queue.put(END);
}
IO.println(time() + " : P has finished");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "P");
// 两个消费者取数字,直到遇到结束标记
var consumers = new Thread[nbConsumers];
for (int i = 0; i < consumers.length; i++) {
consumers[i] = new Thread(() -> {
String name = Thread.currentThread().getName();
try {
while (true) {
// 如果队列为空则阻塞
int number = queue.take();
if (number == END) {
break;
}
IO.println(time() + " : " + name + " took " + number);
// 处理该数字
Thread.sleep(600);
}
IO.println(time() + " : " + name + " has finished");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "C" + (i + 1));
}
// 启动所有线程并等待它们
producer.start();
for (Thread consumer : consumers) {
consumer.start();
}
producer.join();
for (Thread consumer : consumers) {
consumer.join();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 4 行:标记生产结束的值。它是一个常量,声明在任何类之外:它是隐式类的静态字段;
- 第 8 行:一个最多容纳 3 个元素的队列。[ArrayBlockingQueue] 把元素存储在固定大小的数组中;[LinkedBlockingQueue] 默认容量不限;
- 第 12–29 行:生产者把数字 1 到 8 放入队列,每十分之一秒放一个,随后为每个消费者放入一个结束标记(第 22–24 行);
- 第 34–51 行:两个消费者取出数字,并花 0.6 秒处理每一个。它们消费的速度比生产者生成的速度慢;
- 第 39 行:阻塞式移除。每个数字只会被两个消费者中的一个取走;
- 第 40–42 行:取到结束标记的消费者退出其循环。每个消费者取到一个,因此每个消费者对应放入一个标记;
- 生产者和消费者都是包含 [try] 语句的 lambda,因为 [put]、[take] 和 [sleep] 都可能抛出 [InterruptedException]。
结果:
| > java Threads24.java
19:16:25.299 : P put 1 (waiting elements: 0)
19:16:25.304 : C2 took 1
19:16:25.427 : P put 2 (waiting elements: 1)
19:16:25.428 : C1 took 2
19:16:25.531 : P put 3 (waiting elements: 1)
19:16:25.631 : P put 4 (waiting elements: 2)
19:16:25.732 : P put 5 (waiting elements: 3)
19:16:25.927 : C2 took 3
19:16:25.927 : P put 6 (waiting elements: 3)
19:16:26.028 : C1 took 4
19:16:26.029 : P put 7 (waiting elements: 3)
19:16:26.528 : C2 took 5
19:16:26.528 : P put 8 (waiting elements: 3)
19:16:26.652 : C1 took 6
19:16:27.128 : P has finished
19:16:27.129 : C2 took 7
19:16:27.253 : C1 took 8
19:16:27.736 : C2 has finished
19:16:27.854 : C1 has finished
|
我们看到生产者很快放入最初的几个数字,然后,一旦队列中有 3 个元素,只有在消费者取走一个时才能再放入一个数字:队列已满时,它被 [put] 阻塞。消费者彼此分担这些数字,并在取到结束标记时停止。这种节奏是可重现的;而每个数字分配给 C1 还是 C2 则不可重现。生产者只有在其两个结束标记都已放入之后才显示“P has finished”,也就是在 C2 取走数字 7 并腾出一个位置之后。
我们将在下一章讨论异步进程之间的数据传输时再回到阻塞队列。使用虚拟线程时,阻塞在 [take] 上的消费者不会占用任何系统线程。
8.10. 线程池:ExecutorService
8.10.1. 原理
到目前为止,为了管理线程,我们都是先创建它们,再通过 [start()] 启动。创建平台线程是一项相对昂贵的操作:特别是系统必须为它分配一个栈,而且每个线程在存在期间都会占用内存。我们将在第 10 章看到连接池的存在:已打开的连接被保留备用,并借给请求它们的线程,因为打开连接的代价很高。线程也有类似的机制:线程池。
Java 使用 [java.util.concurrent.ExecutorService] 接口(“执行器”)来表示线程池:不再创建线程,而是把任务交给执行器,由它让自己的线程去执行。完成了一个任务的线程不会被销毁,而是继续处理下一个任务。[ThreadPoolExecutor] 类是最常见的实现,其工作方式如下:
- 它拥有固定数量的线程(“核心池大小”):只要尚未达到这个数量,每个新任务都会触发创建一个新线程;
- 超出之后,任务被放入队列 ([BlockingQueue]),线程从中取出任务;
- 如果队列已满,线程池会创建额外的线程,直到达到最大数量(“最大池大小”)。如果这些额外的线程空闲超过一定时间,就会被销毁;
- 如果已达到最大值且队列已满,任务就会被拒绝:默认情况下,提交该任务的方法会抛出 [RejectedExecutionException] 异常。
线程池有两个优点:它节省了创建线程所花的时间(几个线程就能处理数百个请求),并且通过限制线程数量,防止应用程序被过多的请求压垮。
执行器通过其 [shutdown] 方法终止(它不再接受新任务,其线程在已提交的任务完成后停止),之后可以接着调用 [awaitTermination] (等待任务完成),或者通过 [shutdownNow] (中断正在执行的任务)终止。从 Java 19 起,[ExecutorService] 扩展了 [AutoCloseable] 接口:其 [close] 方法调用 [shutdown] ,然后等待所有任务完成。因此,你可以在带资源的 [try] 语句中声明执行器:退出该块时,所有已分配的任务都已完成。[Threads25.java] 程序如下:
| // 线程池:ThreadPoolExecutor
void main() {
Thread.currentThread().setName("Main");
// 3 个常驻线程,最多 5 个线程,等待队列可容纳 2 个任务
try (var pool = new ThreadPoolExecutor(3, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2))) {
// 我们给线程池分配 8 个各 3 秒的任务
for (int i = 0; i < 8; i++) {
var data = new Data(i, LocalTime.now(), 3);
try {
pool.execute(() -> sleep(data, pool));
} catch (RejectedExecutionException e) {
IO.println(time() + " : job no. " + i + " was rejected by the pool");
}
}
IO.println(time() + " : thread Main gave the jobs to the pool and waits for their end");
// try 块结束时关闭线程池:close() 会等待已提交的任务结束
}
IO.println(time() + " : end of thread Main");
}
// 线程池中的线程执行的任务
static void sleep(Data data, ThreadPoolExecutor pool) {
// 线程池的状态
IO.println("%s : job no. %d starts in thread %s (threads: %d, active: %d, queued: %d)"
.formatted(time(), data.number(), Thread.currentThread().getName(),
pool.getPoolSize(), pool.getActiveCount(), pool.getQueue().size()));
// 休眠 [duration] 秒
try {
Thread.sleep(data.duration() * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
double duration = Duration.between(data.start(), LocalTime.now()).toMillis() / 1000.0;
IO.println("%s : job no. %d ends: scheduled for %d s, it lasted %.2f s since its request"
.formatted(time(), data.number(), data.duration(), duration));
}
// 传递给每个任务的信息
record Data(int number, LocalTime start, int duration) {
}
// 当前时间,精确到百分之一秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SS"));
}
|
说明:
- 第 6 行:线程池有 3 个常驻线程,最多 5 个线程;任何空闲 60 秒的额外线程都会被销毁;任务队列是一个有 2 个位置的 [ArrayBlockingQueue] 。线程池在带资源的 [try] 语句中创建;
- 第 8–15 行:向线程池分配 8 个作业,每个持续 3 秒。[execute(Runnable)] 方法把任务分配给线程池,而不等待;
- 第 9 行:每个作业都会收到一个 [Data] 对象;它是一个 [record] (第 40 行),同样定义在任何类之外;
- 第 12–14 行:被线程池拒绝的作业会触发 [RejectedExecutionException] 异常;
- 第 18 行:退出 [try] 块会关闭线程池,并等待已分配的作业完成;
- 第 23–37 行:由线程池中的线程执行的作业。线程名([pool-1-thread-1]……)由线程池提供;
- 第 27 行:线程池的状态:其线程数([getPoolSize])、当前正在执行作业的线程数([getActiveCount])以及在队列中等待的作业数([getQueue().size()]);
- 第 45 行:时间显示到百分之一秒([SS])。
结果:
| > java Threads25.java
19:16:31.71 : job no. 7 was rejected by the pool
19:16:31.72 : thread Main gave the jobs to the pool and waits for their end
19:16:31.62 : job no. 1 starts in thread pool-1-thread-2 (threads: 2, active: 2, queued: 0)
19:16:31.72 : job no. 2 starts in thread pool-1-thread-3 (threads: 5, active: 5, queued: 2)
19:16:31.72 : job no. 6 starts in thread pool-1-thread-5 (threads: 5, active: 5, queued: 2)
19:16:31.71 : job no. 5 starts in thread pool-1-thread-4 (threads: 5, active: 5, queued: 2)
19:16:31.62 : job no. 0 starts in thread pool-1-thread-1 (threads: 2, active: 2, queued: 0)
19:16:34.81 : job no. 2 ends: scheduled for 3 s, it lasted 3.10 s since its request
19:16:34.81 : job no. 3 starts in thread pool-1-thread-3 (threads: 5, active: 5, queued: 1)
19:16:34.82 : job no. 5 ends: scheduled for 3 s, it lasted 3.10 s since its request
19:16:34.82 : job no. 4 starts in thread pool-1-thread-4 (threads: 5, active: 5, queued: 0)
19:16:34.82 : job no. 6 ends: scheduled for 3 s, it lasted 3.10 s since its request
19:16:34.82 : job no. 0 ends: scheduled for 3 s, it lasted 3.21 s since its request
19:16:34.82 : job no. 1 ends: scheduled for 3 s, it lasted 3.20 s since its request
19:16:37.82 : job no. 4 ends: scheduled for 3 s, it lasted 6.10 s since its request
19:16:37.81 : job no. 3 ends: scheduled for 3 s, it lasted 6.10 s since its request
19:16:37.82 : end of thread Main
|
- 作业 0、1 和 2 被分配给为此创建的三个常驻线程;
- 作业 3 和 4 被放入队列,此时队列已满;
- 作业 5 和 6 触发了两个额外线程([pool-1-thread-4] 和 [pool-1-thread-5])的创建:它们立即启动,早于在队列中等待的作业 3 和 4。这就是 [ThreadPoolExecutor] 的规则:先用队列,再创建额外线程——这常常让人感到意外;
- 作业 7 被拒绝:5 个线程都在忙,队列已满;
- 作业 3 和 4 不得不等待,直到第一批作业完成后有线程可用:它们复用了线程 3 和 4。总计,从它们提出请求起花了 6 秒多一点:3 秒的等待和 3 秒的处理;
- 每个作业在启动时显示的值(线程数、队列情况)取决于它获得处理器的确切时刻:每次执行都不同。然而,每个作业的结果(立即执行、在队列中等待或被拒绝)是可重现的。
你很少需要自己构建 *[ThreadPoolExecutor] :*[Executors] 类为常见情形提供了构造方法:
方法 | 返回的执行器 |
[newFixedThreadPool(n)] | 一个包含 n 个常驻线程的线程池,带有容量不限的队列 |
[newCachedThreadPool()] | 一个没有常驻线程的线程池,它按需创建任意多的线程,并销毁空闲 60 秒的线程 |
[newSingleThreadExecutor()] | 单个线程,按任务提交的顺序依次执行任务 |
[newScheduledThreadPool(n)] | 一个能够延迟执行或周期性执行任务的线程池([ScheduledExecutorService] 接口) |
[newVirtualThreadPerTaskExecutor()] | (Java 21)一个没有线程池的执行器,为每个任务创建一个新的虚拟线程 |
最后一种执行器值得说明一下:虚拟线程不放入线程池。它们的开销非常小,因此每个任务都会创建一个新线程;为了限制资源使用,可以使用信号量,就像程序 [Threads15.java] 中那样。
8.10.2. 带结果的任务:Callable 和 Future
[execute] 方法把一个 [Runnable] 传给线程池,它不返回结果。[submit(task)] 方法还接受 [Callable<V>],这是一个函数式接口,其 [V call() throws Exception] 方法返回类型为 V 的结果,并且可以抛出受检异常。它返回一个 [Future<V>] 对象,可用来跟踪任务:
Future<V> 方法 | 作用 |
[V get()]、[V get(long timeout, TimeUnit unit)] | 等待任务完成(最多等待 [timeout] 指定的时长)并返回其结果。如果任务抛出异常,[get] 会抛出一个包装该异常的 [ExecutionException] (方法 [getCause]) |
[boolean isDone()] | 指示任务是否已完成(正常完成、因异常而结束或被取消) |
[Future.State state()] | (Java 19)任务的状态:[RUNNING]、[SUCCESS]、[FAILED] 或 [CANCELLED] |
[V resultNow()]、[Throwable exceptionNow()] | (Java 19)已完成任务的结果或异常,无需等待 |
[boolean cancel(boolean mayInterruptIfRunning)] | 取消任务;如果任务已经开始且 [mayInterruptIfRunning] 等于 [true],则执行该任务的线程会被中断 |
执行器的 [invokeAll(collection of Callable)] 方法提交集合中的所有任务,等待它们全部完成,并按集合的顺序返回它们的 [Future] 值列表。[invokeAny] 方法返回第一个成功完成的任务的结果,并取消其他任务。[Threads26.java] 程序如下:
| // ExecutorService:提交任务并通过 Future 获取结果
void main() throws InterruptedException {
IO.println("Main thread: " + Thread.currentThread());
// 1 - 一个 2 个线程的线程池,在 try 块结束时自动关闭
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
// 三个任务,每个都返回 Integer 类型的结果
var futures = new ArrayList<Future<Integer>>();
for (int i = 0; i < 3; i++) {
int number = i;
futures.add(pool.submit(() -> {
IO.println(time() + " : task " + number + " runs in thread "
+ Thread.currentThread().getName());
// 工作:Callable 可以抛出受检异常
Thread.sleep(500L * (number + 1));
// 任务的结果
return number * 10;
}));
}
// 结果:get() 等待任务结束
for (int i = 0; i < futures.size(); i++) {
Future<Integer> future = futures.get(i);
try {
IO.println("task " + i + " : result " + future.get() + ", state " + future.state());
} catch (ExecutionException e) {
IO.println("task " + i + " failed: " + e.getCause());
}
}
// 一个抛出异常的任务
Future<Integer> failing = pool.submit(() -> fail());
try {
failing.get();
} catch (ExecutionException e) {
// 任务的异常被包装在 ExecutionException 中
IO.println(e.getClass().getSimpleName() + " containing " + e.getCause().getClass().getSimpleName()
+ " : " + e.getCause().getMessage());
}
IO.println("failing task: state " + failing.state());
}
// 2 - 每个任务一个虚拟线程;invokeAll 提交一个任务集合并等待它们结束
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Callable<String>> jobs = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int number = i;
jobs.add(() -> {
Thread.sleep(300);
return "job " + number + " executed by " + Thread.currentThread();
});
}
for (Future<String> future : executor.invokeAll(jobs)) {
// 任务已结束:resultNow() 无需等待即可返回其结果
IO.println(future.resultNow());
}
}
}
// 失败任务的工作
static int fail() {
throw new IllegalStateException("test....");
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 7 行:由 [Executors.newFixedThreadPool(2)] 创建的 2 个线程的线程池,在 [try] 块结束时关闭;
- 第 12–19 行:每个任务都是一个 lambda,它显示执行自己的线程,休眠 0.5、1 或 1.5 秒,然后返回一个整数结果。由于该 lambda 返回一个值,编译器把它解释为 [Callable<Integer>],而 [submit] 返回一个 [Future<Integer>]。第 16 行的 [sleep] 不需要包含在 [try] 中:[Callable] 的 [call] 方法声明了 [throws Exception];
- 第 25 行:[future.get()] 等待任务完成并返回其结果;[future.state()] 返回其状态;
- 第 32 行:一个执行 [fail] 方法(第 61–63 行)的任务,该方法会抛出异常;
- 第 34–38 行:任务中抛出的异常不会丢失:它被存储在 [Future] 对象中,然后在请求结果的线程中被重新抛出,包装在一个 [ExecutionException] 中,其 [getCause] 方法会抛出原始异常;
- 第 44–57 行:一个为每个任务创建一个虚拟线程的执行器。方法 [invokeAll] (第 53 行)把列表 [jobs] 中的三个作业分配给它,并等待它们完成。任务完成后,[resultNow] (第 55 行)立即返回它们的结果。
结果:
| > java Threads26.java
Main thread: Thread[#3,main,5,main]
19:16:39.815 : task 0 runs in thread pool-1-thread-1
19:16:39.816 : task 1 runs in thread pool-1-thread-2
19:16:40.333 : task 2 runs in thread pool-1-thread-1
task 0 : result 0, state SUCCESS
task 1 : result 10, state SUCCESS
task 2 : result 20, state SUCCESS
ExecutionException containing IllegalStateException : test....
failing task: state FAILED
job 0 executed by VirtualThread[#25]/runnable@ForkJoinPool-1-worker-1
job 1 executed by VirtualThread[#27]/runnable@ForkJoinPool-1-worker-2
job 2 executed by VirtualThread[#30]/runnable@ForkJoinPool-1-worker-1
|
- 任务在线程池的线程([pool-1-thread-1] 和 [pool-1-thread-2])中运行;
- 任务 2 直到任务 0 完成后才启动,使用的是任务 0 释放出来的线程:线程池只有 2 个线程,任务 2 在队列中等待。这一现象是可重现的;
- 结果在任务完成之后才被取出,它们的状态为 [SUCCESS];
- 失败任务抛出的异常被主线程捕获,该任务的状态为 [FAILED];
- 第二部分中的三个作业由三个不同的虚拟线程执行,它们挂载在载体线程 [ForkJoinPool-1-worker-1] 和 [ForkJoinPool-1-worker-2] 上。
在 [get] 中阻塞线程以等待结果很简单,但这样无法在不等待的情况下把处理操作链接到任务的完成上。下一章介绍的 [CompletableFuture] 类可以做到这一点。最后请注意,Java 25 以预览形式提供了结构化并发 ([StructuredTaskScope]),它把一组子任务视为单一的工作单元(如果其中一个失败,其余的会被中止);由于它尚未定稿,本课程不使用它。
8.11. 数据并行
8.11.1. 并行流
让我们回到线程的第一个用途:利用所有处理器完成耗时的计算。Stream API(第 5 章)中的流可以并行执行:只需对流调用 [parallel()] ,或者对集合调用 [parallelStream()] 而不是 [stream()]。这样,流就会把数据划分成块,由多个线程处理这些块,然后合并各部分结果。所使用的线程来自共享池 ([ForkJoinPool.commonPool()]),再加上执行该流的线程。默认情况下,共享池的线程数等于处理器数减一:调用线程也参与计算。
只有当每个元素的处理独立 于其他元素时,这类流才适用:处理顺序是未定义的,而且如果处理过程会更新共享数据,就必须对其加以保护。程序 [Threads27.java] 如下:
| // 并行流:parallelStream 和 IntStream.parallel
void main() {
// 1 - 统计小于 N 的素数个数
final int N = 5_000_000;
// 顺序版本:for 循环
long start = System.nanoTime();
int nbSequential = 0;
for (int i = 2; i < N; i++) {
if (isPrime(i)) {
nbSequential++;
}
}
IO.println("sequential for : %,d prime numbers in %d ms"
.formatted(nbSequential, since(start)));
// 顺序版本:流
start = System.nanoTime();
long nbStream = IntStream.range(2, N).filter(i -> isPrime(i)).count();
IO.println("sequential stream : %,d prime numbers in %d ms".formatted(nbStream, since(start)));
// 并行版本:同样的流,改为并行
start = System.nanoTime();
long nbParallel = IntStream.range(2, N).parallel().filter(i -> isPrime(i)).count();
IO.println("parallel stream : %,d prime numbers in %d ms".formatted(nbParallel, since(start)));
// 参与工作的线程,以及每个线程找到的素数个数
var threads = new ConcurrentHashMap<String, Integer>();
IntStream.range(2, N).parallel()
.filter(i -> isPrime(i))
.forEach(i -> threads.merge(Thread.currentThread().getName(), 1, Integer::sum));
new TreeMap<>(threads).forEach((name, nb) ->
IO.println(" thread %-30s : %,d prime numbers found".formatted(name, nb)));
// 2 - 并行处理集合
List<String> files = List.of("a.txt", "b.txt", "c.txt", "d.txt", "e.txt");
files.parallelStream().forEach(file -> {
IO.println(time() + " : processing of " + file + " in thread "
+ Thread.currentThread().getName());
// 模拟处理
sleep(500);
});
IO.println("parallel forEach finished");
IO.println("Parallelism of the common pool: " + ForkJoinPool.getCommonPoolParallelism());
}
// 素性测试(刻意写得简单)
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
// 自 [start] 起经过的毫秒数(以纳秒为单位)
static long since(long start) {
return (System.nanoTime() - start) / 1_000_000;
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 当前时间,精确到毫秒
static String time() {
return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
}
|
说明:
- 第 7–15 行:使用标准的 [for] 循环统计小于 5,000,000 的质数。函数 [isPrime] (第 48–58 行)测试不超过该数平方根的除数:这是一个耗时的过程,而且各次迭代相互独立;
- 第 18–20 行:使用顺序流水线进行同样的计算:[IntStream.range(2, N)] 生成从 2 到 N–1 的整数,[filter] 只保留质数,[count] 负责计数;
- 第 23–25 行:同一个流,通过 [parallel()] 变为并行。其他地方无需任何改动:每个线程统计自己所负责数据段中的质数,流再把各部分的计数相加。线程之间不共享任何数据;
- 第 28–33 行:为了确定哪些线程完成了工作,并行流为每个线程统计它所发现的质数,并把它们存储在共享的 [ConcurrentHashMap] 中。这是共享数据,通过原子操作([merge])进行更新;
- 第 36–42 行:方法
***[parallelStream()]接收一个文件名列表,返回一个并行流;*[forEach] 处理每个文件(处理过程用半秒的暂停来模拟)。对于并行流,[forEach] 不保留列表的顺序;[forEachOrdered] 则会保留顺序,但要牺牲一部分并行性;
- 第 44 行:共享池中的线程数。
结果:
| > java Threads27.java
sequential for : 348,513 prime numbers in 1419 ms
sequential stream : 348,513 prime numbers in 1253 ms
parallel stream : 348,513 prime numbers in 780 ms
thread ForkJoinPool.commonPool-worker-1 : 224,082 prime numbers found
thread main : 124,431 prime numbers found
19:16:47.328 : processing of b.txt in thread ForkJoinPool.commonPool-worker-1
19:16:47.328 : processing of c.txt in thread main
19:16:47.838 : processing of a.txt in thread ForkJoinPool.commonPool-worker-1
19:16:47.838 : processing of e.txt in thread main
19:16:48.339 : processing of d.txt in thread ForkJoinPool.commonPool-worker-1
parallel forEach finished
Parallelism of the common pool: 1
|
- 三个版本找到的质数个数相同;
- 有两个线程参与了并行处理:线程 [main] 和共享池中唯一的线程([ForkJoinPool.commonPool-worker-1]):在这台双处理器机器上,共享池只有一个线程(第 13 行);
- 文件处理成对进行,间隔半秒,且顺序与列表不一致;
- 并行流更快,但并没有快一倍:在截取结果时,我们程序中的线程与其他非常活跃的程序共享这两个处理器,测得的时间在不同次运行之间差异很大。在负载较轻、有 n 个处理器的机器上,像这样的并行流可以比顺序流快近 n 倍。下结论之前务必先测量:并行化是有代价的(工作划分、同步、合并结果),只有当处理每个元素需要大量计算时,这些代价才值得。
8.11.2. 分而治之:ForkJoinPool 和 RecursiveTask
并行流基于 Fork/Join框架(Java 7),该框架也可以直接使用。它非常适合“分而治之”算法:过大的任务被分解为子任务,子任务再继续分解,直到各部分小到可以直接处理;然后合并子任务的结果。任务是派生自 [RecursiveTask<V>] (返回类型为 V 的结果的任务)或 [RecursiveAction] (无结果)的类,需要重写其方法 [compute]。在 [compute] 中,子任务的 [fork()] 方法立即把它提交给线程池,而其 [join()] 方法则等待其结果。
任务由 [ForkJoinPool] 执行,其中每个线程都有自己的任务队列。无事可做的线程会从另一个线程的队列中“窃取”任务(“工作窃取”):负载因此被自动分配。承载虚拟线程的线程也构成一个 [ForkJoinPool]:这就是我们在虚拟线程的文本表示中看到的那个([ForkJoinPool-1-worker-1])。程序 [Threads28.java] 使用递归任务统计质数:
| // 分而治之:ForkJoinPool 和 RecursiveTask
void main() {
final int N = 5_000_000;
// 公共池,并行流默认使用
long start = System.nanoTime();
int nb = ForkJoinPool.commonPool().invoke(new CountPrimes(2, N));
IO.println("common pool : %,d prime numbers in %d ms".formatted(nb, since(start)));
// 一个 4 个线程的线程池,在 try 块结束时关闭
try (var pool = new ForkJoinPool(4)) {
CountPrimes.chunks.clear();
start = System.nanoTime();
nb = pool.invoke(new CountPrimes(2, N));
IO.println("pool of 4 threads : %,d prime numbers in %d ms".formatted(nb, since(start)));
IO.println("tasks stolen by one thread from another: " + pool.getStealCount());
}
// 各数据块在最后一个线程池的各线程之间的分布
new TreeMap<>(CountPrimes.chunks).forEach((name, nbChunks) ->
IO.println(" %-25s : %d chunks processed".formatted(name, nbChunks)));
}
// 统计区间 [start, end[ 内素数个数的任务
static class CountPrimes extends RecursiveTask<Integer> {
@Serial
private static final long serialVersionUID = 1L;
// 低于此阈值,数据块直接处理
private static final int THRESHOLD = 100_000;
// 每个线程处理的数据块数
static final Map<String, Integer> chunks = new ConcurrentHashMap<>();
private final int start;
private final int end;
CountPrimes(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
// 数据块足够小:我们按顺序处理
if (end - start <= THRESHOLD) {
chunks.merge(Thread.currentThread().getName(), 1, Integer::sum);
int nb = 0;
for (int i = start; i < end; i++) {
if (isPrime(i)) {
nb++;
}
}
return nb;
}
// 否则,我们将其一分为二
int middle = (start + end) >>> 1;
var left = new CountPrimes(start, middle);
var right = new CountPrimes(middle, end);
// 左半部分交给线程池(另一个线程可能会“窃取”它)
left.fork();
// 右半部分由当前线程处理
int nbRight = right.compute();
// 我们等待左半部分的结果,并合并两个结果
return left.join() + nbRight;
}
}
// 素性测试(刻意写得简单)
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
// 自 [start] 起经过的毫秒数(以纳秒为单位)
static long since(long start) {
return (System.nanoTime() - start) / 1_000_000;
}
|
说明:
- 第 24–64 行:任务 [CountPrimes] 统计区间 [start, end[ 中的质数。它派生自 [RecursiveTask<Integer>];
- 第 25–26 行:Fork/Join 任务是可序列化的:因此编译器选项 [-Xlint:all] 要求声明序列化版本号 [serialVersionUID],并使用注解 [@Serial] (Java 14);
- 第 28 行:对于少于 100,000 个数的区间,直接处理;
- 第 30 行:每个线程已处理的块数;
- 第 43–52 行:足够小的块按顺序处理;
- 第 54–56 行:过大的块被拆分为两个子任务。表达式 [(start + end) >>> 1] 使用无符号右移计算中间值,这样可以防止和超出 [int] 的容量时发生溢出;
- 第 58 行:左半部分被分配给线程池;另一个线程可能会“窃取”它;
- 第 60 行:右半部分由当前线程通过直接调用 [compute] 来处理。没有必要把两半都分配给线程池:当前线程将无事可做,只能等待;
- 第 62 行:线程等待左半部分的结果(如果没有人“窃取”它,线程会自己处理),并合并两个结果;
- 第 7 行:任务首先由共享池执行。[invoke(task)] 方法提交任务并等待其结果;
- 第 11–17 行:然后由一个 4 线程的线程池执行,该线程池是在带资源的 [try] 语句中创建的([ForkJoinPool] 是一个 [ExecutorService])。[getStealCount] 方法返回一个线程从另一个线程那里窃取的任务数;
- 第 19–20 行:块在该线程池各线程之间的分布情况。
结果:
| > java Threads28.java
common pool : 348,513 prime numbers in 1506 ms
pool of 4 threads : 348,513 prime numbers in 648 ms
tasks stolen by one thread from another: 6
ForkJoinPool-1-worker-1 : 15 chunks processed
ForkJoinPool-1-worker-2 : 19 chunks processed
ForkJoinPool-1-worker-3 : 12 chunks processed
ForkJoinPool-1-worker-4 : 18 chunks processed
|
- 共享池并不比顺序循环快(与前一个程序比较):在这台机器上,它只有一个线程,而在 [invoke] 中等待结果的主线程并不像在并行流中那样参与计算;
- 4 线程的线程池用上了两个处理器,速度大约快了一倍。对于纯计算来说,线程数多于处理器数没有好处,但在这里代价也不大;
- 64 个块(5,000,000 / 100,000,因对半拆分而向上取整为 2 的幂)借助任务窃取,大致均匀地分配给了 4 个线程。这种分布每次运行都不同。
大多数情况下并行流就足够了;只有对于难以用流表达的递归算法(排序、树遍历等),才需要编写 Fork/Join 任务。
8.12. 线程本地数据
8.12.1. 原理
考虑一个三层应用程序:

假设该应用程序是多用户的,例如一个 Web 应用程序。每个用户请求由一个线程处理。线程的生命周期如下:
- 创建线程(虚拟线程),或从线程池中请求一个线程来满足用户的请求;
- 如果该请求需要数据,线程就执行 [ui] 层中的一个方法,该方法调用 [business] 层中的一个方法,后者又调用 [dao] 层中的一个方法;
- 线程把响应返回给用户。然后它要么终止,要么被归还给线程池。
在第二步中,让线程拥有自己的数据(即不与其他线程共享的数据)可能会很有用。例如,这些数据可以属于该线程正在服务的特定用户,并在各个 [ui, business, dao] 层中使用,而无需作为参数传给每个方法。
Java 为此提供了两种工具:
- [ThreadLocal<T>] 类(Java 1.2):一个对象,其值(由 [get()] 读取,由 [set(value)] 写入)对每个线程都是不同的。构造方法 [ThreadLocal.withInitial(supplier)] 为每个线程提供初始值;方法 [remove()] 清除当前线程的值。派生类 [InheritableThreadLocal<T>] 把创建线程持有的值传递给新创建的线程;
- [ScopedValue<T>] 类(Java 25 中已定稿):一个在代码的限定作用域内绑定到某个线程的值,并且在该作用域内不能被修改。
8.12.2. ThreadLocal 类
程序 [Threads29.java] 比较了普通静态字段、[ThreadLocal] 和 [InheritableThreadLocal]:
| // 线程局部数据:ThreadLocal 和 InheritableThreadLocal
void main() throws InterruptedException {
Thread.currentThread().setName("Main");
// 主线程写入其自己的值
Context.shared = 100;
Context.perThread.set(100);
Context.user.set("admin");
Context.language.set("fr");
// 三个线程先写入再读回数据
var threads = new Thread[3];
for (int i = 0; i < threads.length; i++) {
int number = i;
threads[i] = new Thread(() -> {
// 写入
Context.shared = number;
Context.perThread.set(number);
// 线程 T2 不设置用户:它将得到初始值
if (number != 2) {
Context.user.set("user" + number);
}
// 线程 T1 修改从主线程继承的语言
if (number == 1) {
Context.language.set("en");
}
// 我们让其他线程依次写入
sleep(200);
// 读回
display();
}, "T" + i);
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
// 主线程读回
display();
}
// 显示当前线程所见的数据
static void display() {
IO.println("%-4s : shared=%-3d perThread=%-3d user=%-20s language=%s".formatted(
Thread.currentThread().getName(), Context.shared, Context.perThread.get(),
Context.user.get(), Context.language.get()));
}
// 程序的数据
static class Context {
// 静态(volatile)字段:只有一份副本,由所有线程共享
static volatile int shared;
// 每个线程一份副本;初始值为 null
static final ThreadLocal<Integer> perThread = new ThreadLocal<>();
// 每个线程一份副本,由提供的工厂为每个线程初始化
static final ThreadLocal<String> user =
ThreadLocal.withInitial(() -> "anonymous (thread " + Thread.currentThread().getName() + ")");
// 每个线程一份副本,其初始值继承自创建它的线程
static final InheritableThreadLocal<String> language = new InheritableThreadLocal<>();
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
|
说明:
- 第 51 行:普通静态字段。它只有一个实例,被所有线程共享。它是 [volatile] 的,因此每个线程都能看到其他线程写入的最新值;
- 第 53 行:一个 [ThreadLocal<Integer>] 对象。每个线程都有自己的值;只要线程还没有写入,[get] 就返回 [null];
- 第 55–56 行:由 [ThreadLocal<String>] 对象通过 [ThreadLocal.withInitial(…)] 创建。传给该方法的 lambda 会在线程第一次读取尚未写入的值时执行;它为该线程提供初始值;
- 第 58 行:一个 [InheritableThreadLocal<String>] 对象:线程创建时,其初始值是创建线程当时所持有值的副本;
- 第 6–9 行:主线程写入自己的值;
- 第 17–26 行:每个线程写入自己的值,只有线程 T2 不设置用户,且线程 T1 是唯一修改语言的线程;
- 第 28 行:每个线程等待其他线程写入完毕后,再重新读取这些值;
- 第 42–46 行:显示当前线程所看到的数据。
结果:
| > java Threads29.java
T1 : shared=2 perThread=1 user=user1 language=en
T0 : shared=2 perThread=0 user=user0 language=fr
T2 : shared=2 perThread=2 user=anonymous (thread T2) language=fr
Main : shared=2 perThread=100 user=admin language=fr
|
- 普通字段 [shared] 对所有线程具有相同的值:最后写入的值(在这次执行中是线程 T2 的值;另一次执行可能得到不同的值);
- [perThread] 在每个线程中都保留了该线程写入的值;
- [user] 具有每个线程写入的值;没有写入过它的线程 T2 得到了由 [withInitial] 的 lambda 提供的初始值;
- [language] 对于线程 T0 和 T2 等于 [fr] ,它们从主线程继承了该值,且从未写入过它。线程 T1 把它改为 [en] ,但只对它自己生效:主线程和其他线程看不到这一修改。
使用 [ThreadLocal] 需要一些预防措施。线程的值只在线程本身存在期间有效:使用线程池时,处理完一个请求的线程随后还会处理其他请求,因此必须在每个请求结束时调用 [remove];否则,下一个请求会发现上一个请求遗留的数据(而且内存永远不会被释放)。使用虚拟线程时,可以创建数百万个线程,每个线程都有自己的数据副本:[InheritableThreadLocal] 随后会把它的值复制到其中的每一个线程中。最后,一个可以被线程的任何方法修改的值会让代码难以理解。[ScopedValue] 类避免了这些问题。
8.12.3. ScopedValue 类
[ScopedValue<T>] 值在一段代码的执行期间被绑定到某个值,这段代码称为它的作用域:
- [ScopedValue.newInstance()] 创建一个可绑定的值,通常存储在 [static final] 字段中;
- [ScopedValue.where(sv, value).run(action)] 通过把 [sv] 绑定到 [value] 来执行该操作(一个 [Runnable])。在当前线程中执行该操作及其调用的所有方法期间,[sv.get()] 返回 [value]。操作结束时,绑定即消失:无需任何清理;
- [ScopedValue.where(sv, value).call(op)] 对返回结果的操作做同样的事;
- 在作用域内,值不能被修改;它只能在嵌套作用域中被绑定到另一个值;
- [isBound()] 指示该值在当前线程中是否已绑定;[orElse(other)] 返回该值,如果未绑定,则返回 [other]。在任何作用域之外,[get()] 会抛出 [NoSuchElementException] 异常。
程序 [Threads30.java] 如下:
| // 绑定到作用域的值:ScopedValue(Java 25)
// 代码代表其运行的用户
static final ScopedValue<String> USER = ScopedValue.newInstance();
void main() throws InterruptedException {
IO.println("Outside of any scope, is USER bound? " + USER.isBound());
try {
USER.get();
} catch (NoSuchElementException e) {
IO.println("get() out of scope: " + e.getClass().getSimpleName());
}
// 1 - 两个同时进行的处理,各自对应其用户
Thread t1 = Thread.ofVirtual().start(() -> ScopedValue.where(USER, "alice").run(this::process));
Thread t2 = Thread.ofVirtual().start(() -> ScopedValue.where(USER, "bob").run(this::process));
t1.join();
t2.join();
// 2 - 一个作用域可以包含另一个作用域,后者临时绑定另一个值
ScopedValue.where(USER, "admin").run(() -> {
display("outer scope");
ScopedValue.where(USER, "guest").run(() -> display("inner scope"));
display("back in the outer scope");
// 在作用域中创建的线程不继承该绑定
Thread child = Thread.ofVirtual().start(
() -> IO.println("child thread: bound? " + USER.isBound()));
try {
child.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 3 - call:返回结果的带绑定的处理
String message = ScopedValue.where(USER, "carole").call(() -> "hello " + USER.get());
IO.println(message);
// 作用域结束后,绑定消失
IO.println("After the scopes: bound? " + USER.isBound()
+ ", orElse: " + USER.orElse("nobody"));
}
// [business] 层调用 [dao] 层,而不向其传递用户
void process() {
display("[business] layer");
dao();
}
// [dao] 层在当前作用域中找到用户
void dao() {
display("[dao] layer");
}
// 显示当前作用域中绑定的用户
static void display(String place) {
IO.println(place + " : USER = " + USER.get());
}
|
说明:
- 第 4 行:绑定值 [USER],隐式类的静态字段;
- 第 7–12 行:在任何作用域之外,该值未绑定,[get] 会抛出异常;
- 第 15–16 行:两个虚拟线程执行方法 [process],各自处在 [USER] 绑定到不同用户的作用域中;
- 第 44–52 行:方法 [process] ([business] 层)调用方法 [dao] ([dao] 层),但不向其传递用户:两者各自通过 [USER.get()] 获取用户(第 56 行);
- 第 21–33 行:[USER] 等于 [admin] 的作用域中包含一个嵌套作用域(第 23 行),其中它等于 [guest]。退出嵌套作用域后,我们又看到 [admin];
- 第 26–27 行:在作用域内创建的线程看不到该绑定:与
*[InheritableThreadLocal]* 不同,*[ScopedValue] 不会传递给由 *[Thread] 创建的线程。不过,它会传递给结构化并发的子任务([StructuredTaskScope],Java 25 中为预览),后者确保这些子任务在作用域结束之前完成;
- 第 36 行:[call] 在作用域内执行一个操作并返回其结果;
- 第 39–40 行:作用域结束之后,该值不再被绑定。
结果:
| > java Threads30.java
Outside of any scope, is USER bound? false
get() out of scope: NoSuchElementException
[business] layer : USER = alice
[dao] layer : USER = alice
[business] layer : USER = bob
[dao] layer : USER = bob
outer scope : USER = admin
inner scope : USER = guest
back in the outer scope : USER = admin
child thread: bound? false
hello carole
After the scopes: bound? false, orElse: nobody
|
第 4–7 行中来自虚拟线程的消息可能以不同的顺序出现(bob 先于 alice);其余部分是可重现的。[ScopedValue] 适用于“向下”传递的上下文数据,即从调用者传给被调用的方法:已认证的用户、事务、区域设置等。当被调用的方法需要修改数据以供后续处理时,则需要使用 [ThreadLocal]。
8.12.4. 应用:跨层共享的事务
考虑下面这个三层应用程序,其中 [dao] 层管理一张商品表:

假设 [dao] 层的接口最初如下:
| interface IDao {
int insertArticle(Article article);
List<Article> getAllArticles();
void deleteAllArticles();
}
|
后来,出现了在事务中插入一组商品的需求,因为系统必须以“要么全部成功、要么全部不做”的方式运行:要么插入所有商品,要么一个都不插入。可以向接口中添加一个名为 [insertArticles(List<Article> articles)] 的方法。随后,另一个应用程序又需要在事务中删除一组商品……为了满足不同的业务需求,[dao] 层会不断膨胀。我们可以换一种做法:
- 在 [dao] 层中只包含基本操作(插入、更新、删除、读取一件商品);
- 把同时更新多件商品的操作移到 [business] 层。这些操作使用 [dao] 层的基本操作。
这种方案的优点是,同一个 [dao] 层无需修改,就可以与不同的 [business] 层配合使用。它带来了一个挑战:如何管理把需要原子执行的更新组合在一起的事务:
- 事务必须由 [business] 层在调用 [dao] 层的方法之前启动;
- [dao] 层的方法必须知道事务的存在,才能参与其中;
- 事务必须由 [business] 层来结束(提交或取消)。
为了让 [dao] 层的方法知道正在进行的事务,可以把事务作为参数添加到 [dao] 层的每个方法中。这个参数就会出现在接口方法的签名中,从而把接口与某个特定的数据源绑定在一起。线程本地数据提供了一种更优雅的解决方案:[business] 层把事务放入线程本地数据中,[dao] 层再从那里取出它。[dao] 层的方法签名无需更改。多个线程(多个用户)可以同时工作:每个线程都有自己的事务。
数据库将在第 10 章和第 11 章中介绍。为了把重点放在线程上,这里使用内存中的表和模拟的事务。程序 [Threads31.java] 把所有层合并到一个紧凑的源文件中。实体如下:
| // 一件商品
record Article(int id, String name, double price, int currentStock, int minimumStock) {
}
// 模拟事务:它记录如何撤销每次更新
static class Transaction {
private static final AtomicInteger counter = new AtomicInteger();
private final Deque<Runnable> undos = new ArrayDeque<>();
private final int number = counter.incrementAndGet();
int getNumber() {
return number;
}
// 记录撤销某次更新的操作
void log(Runnable undo) {
undos.push(undo);
}
// 提交事务:更新被保留
void commit() {
undos.clear();
}
// 回滚事务:更新被撤销,从最后一个到第一个
void rollback() {
Runnable undo;
while ((undo = undos.poll()) != null) {
undo.run();
}
}
}
// 各层共享的线程局部数据
static class ThreadContext {
// 线程的当前事务(如果没有则为 null)
static final ThreadLocal<Transaction> transaction = new ThreadLocal<>();
}
|
- 第 68 行:商品是一个 [record],其标识符 [id] 由 [dao] 层设置;
- 第 72–98 行:一个模拟的事务。在事务中进行的每次更新都会记录可用于回滚它的操作(方法 [log]);[commit] 提交事务,同时忽略这些操作;[rollback] 通过从最后一个到第一个依次执行这些回滚操作来回滚事务。这些操作存储在一个栈中:[Deque] 的 [push] 方法向栈顶添加元素,而 [poll] 方法从栈顶移除元素(如果栈为空则返回 [null])。真实的数据库也以类似的方式工作,使用事务日志;
- 第 75 行:每个事务都被分配一个唯一的编号。由于事务可能由多个线程同时创建,计数器是一个 [AtomicInteger],以原子方式递增;
- 第 101–104 行:各层共享的线程本地数据:线程当前的事务,如果没有则为 [null]。
[dao] 层如下:
| // [dao] 层:内存中的商品表,对名称有唯一性约束
interface IDao {
int insertArticle(Article article);
List<Article> getAllArticles();
void deleteAllArticles();
}
static class Dao implements IDao {
// 表及其锁,由所有线程共享
private final List<Article> table = new ArrayList<>();
private final Object lock = new Object();
private int nextId = 1;
@Override
public int insertArticle(Article article) {
// 当前线程中是否有正在进行的事务?
Transaction transaction = ThreadContext.transaction.get();
synchronized (lock) {
if (table.stream().anyMatch(a -> a.name().equals(article.name()))) {
throw new IllegalStateException("an article named [" + article.name() + "] already exists");
}
Article inserted = new Article(nextId++, article.name(), article.price(),
article.currentStock(), article.minimumStock());
table.add(inserted);
// 在事务中,我们记录如何撤销插入
if (transaction != null) {
transaction.log(() -> {
synchronized (lock) {
table.remove(inserted);
}
});
}
String mode = transaction == null
? "outside a transaction"
: "in transaction " + transaction.getNumber();
IO.println("[" + Thread.currentThread().getName() + "] [dao] insertion of " + inserted.name()
+ " (id " + inserted.id() + ") " + mode);
return 1;
}
}
@Override
public List<Article> getAllArticles() {
synchronized (lock) {
return List.copyOf(table);
}
}
@Override
public void deleteAllArticles() {
synchronized (lock) {
table.clear();
}
}
}
|
- 第 117 行:商品表,由所有线程共享。对它的访问由第 118 行的锁保护;
- 第 124 行:方法 [insertArticle] 从当前线程的本地数据中取出 [business] 层可能放入的事务;
- 第 126–128 行:该表对商品名称有唯一性约束:插入名称已存在的商品会抛出异常;
- 第 129–131 行:插入的商品是所收到商品的副本,其标识符由 [dao] 层分配。由于 [record] 对象是只读的,因此会创建一个新对象;
- 第 133–139 行:如果存在事务,[dao] 层就通过记录如何回滚此次插入来参与其中。回滚 lambda 捕获变量 [inserted];
- 第 140–144 行:跟踪输出显示线程、插入的商品以及可能存在的事务;
- 第 150–154 行:返回的商品列表是表的只读副本([List.copyOf]),这样调用者在遍历时就不会受到另一个线程同时修改的影响。
[business] 层如下:
| // [business] 层
interface IBusiness {
void insertArticlesInTransaction(List<Article> articles);
void insertArticlesOutOfTransaction(List<Article> articles);
List<Article> getAllArticles();
void deleteAllArticles();
}
static class Business implements IBusiness {
private final IDao dao;
Business(IDao dao) {
this.dao = dao;
}
// 插入商品列表:要么全部成功,要么全部失败
@Override
public void insertArticlesInTransaction(List<Article> articles) {
// 事务开始,存储在线程局部数据中
var transaction = new Transaction();
ThreadContext.transaction.set(transaction);
try {
for (Article article : articles) {
// [dao] 层将在线程中找到该事务
dao.insertArticle(article);
// 模拟处理,给其他线程留出介入的时间
sleep(200);
}
transaction.commit();
IO.println("[" + Thread.currentThread().getName() + "] [business] transaction "
+ transaction.getNumber() + " committed");
} catch (RuntimeException e) {
transaction.rollback();
IO.println("[" + Thread.currentThread().getName() + "] [business] transaction "
+ transaction.getNumber() + " rolled back");
// 异常被重新抛给调用者
throw e;
} finally {
// 线程不再有正在进行的事务
ThreadContext.transaction.remove();
}
}
// 不使用事务插入商品列表
@Override
public void insertArticlesOutOfTransaction(List<Article> articles) {
for (Article article : articles) {
dao.insertArticle(article);
}
}
@Override
public List<Article> getAllArticles() {
return dao.getAllArticles();
}
@Override
public void deleteAllArticles() {
dao.deleteAllArticles();
}
}
|
- 第 176–180 行:[dao] 层通过构造函数注入;
- 第 186–187 行:[insertArticlesInTransaction] 方法启动一个事务,并把它保存在线程的本地数据中;
- 第 191 行:对每件商品调用 [dao] 层的插入方法,但不向其传递事务;
- 第 193 行:用一次暂停模拟处理过程,以便让另一个线程有时间在事务期间介入(测试程序的第三部分);
- 第 195 行:如果程序执行到这里,说明没有发生异常:提交事务;
- 第 198–203 行:如果发生异常,则回滚事务,并把异常重新抛给调用者;
- 第 206 行:无论哪种情况,线程都不再有活动的事务:[remove()] 从线程中移除事务 ID。如果线程会被重用(池化线程),这一点至关重要;
- 第 212–216 行:同样的插入,但不使用事务。
测试程序如下:
| // 线程局部数据:[business] 层将事务放入其中,[dao] 层从中找到它
void main() throws InterruptedException {
// 应用程序的各层
IDao dao = new Dao();
IBusiness business = new Business(dao);
Thread.currentThread().setName("Main");
// 两个同名商品:第二个违反名称的唯一性约束
List<Article> articles = List.of(new Article(0, "article", 100, 10, 1),
new Article(0, "article", 100, 10, 1));
// 1 - 在事务之外插入
IO.println("Inserting the articles outside a transaction...");
execute(() -> business.insertArticlesOutOfTransaction(articles));
displayArticles(business);
// 2 - 在事务中插入
business.deleteAllArticles();
IO.println("Inserting the articles in a transaction...");
execute(() -> business.insertArticlesInTransaction(articles));
displayArticles(business);
// 3 - 两个同时运行的线程:线程 A 的事务对线程 B 不可见
business.deleteAllArticles();
IO.println("Two simultaneous threads...");
List<Article> articlesA = List.of(new Article(0, "keyboard", 20, 5, 1), new Article(0, "mouse", 10, 5, 1),
new Article(0, "keyboard", 20, 5, 1));
List<Article> articlesB = List.of(new Article(0, "screen", 150, 2, 1));
var threadA = new Thread(() -> execute(() -> business.insertArticlesInTransaction(articlesA)), "A");
var threadB = new Thread(() -> execute(() -> business.insertArticlesOutOfTransaction(articlesB)), "B");
threadA.start();
Thread.sleep(100);
threadB.start();
threadA.join();
threadB.join();
displayArticles(business);
}
// 执行一个操作,并显示可能出现的异常
static void execute(Runnable action) {
try {
action.run();
} catch (RuntimeException e) {
IO.println("[" + Thread.currentThread().getName() + "] " + e.getClass().getSimpleName()
+ " : " + e.getMessage());
}
}
// 休眠 [ms] 毫秒
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 显示商品列表
static void displayArticles(IBusiness business) {
IO.println("List of articles:");
for (Article article : business.getAllArticles()) {
IO.println(" " + article);
}
}
|
- 第 10 行:我们创建一个包含两件同名商品的列表。尝试插入第二件商品会被拒绝。如果在事务之外执行插入,第一件商品会被插入并保留在列表中。如果在事务中执行,第一件商品会被插入,然后在事务回滚时被移除;
- 第 13–16 行:在事务之外插入该列表,然后显示表;
- 第 18–22 行:在事务中执行同样的过程;
- 第 24–37 行:两个线程同时工作。线程 A 在事务中插入三件商品(第三件违反唯一性约束);与此同时,线程 B 在事务之外插入一件商品;
- 第 41–48 行:方法 [execute] 执行一个动作,并显示可能出现的异常,前面带有线程名。
结果:
| > java Threads31.java
Inserting the articles outside a transaction...
[Main] [dao] insertion of article (id 1) outside a transaction
[Main] IllegalStateException : an article named [article] already exists
List of articles:
Article[id=1, name=article, price=100.0, currentStock=10, minimumStock=1]
Inserting the articles in a transaction...
[Main] [dao] insertion of article (id 2) in transaction 1
[Main] [business] transaction 1 rolled back
[Main] IllegalStateException : an article named [article] already exists
List of articles:
Two simultaneous threads...
[A] [dao] insertion of keyboard (id 3) in transaction 2
[B] [dao] insertion of screen (id 4) outside a transaction
[A] [dao] insertion of mouse (id 5) in transaction 2
[A] [business] transaction 2 rolled back
[A] IllegalStateException : an article named [keyboard] already exists
List of articles:
Article[id=4, name=screen, price=150.0, currentStock=2, minimumStock=1]
|
- 在事务之外的插入使第一条记录留在了表中(第 6 行)。[record] 的 [toString] 方法显示其每个组件的名称和值;
- 在事务中进行的插入没有在表中留下任何记录:ID 为 2 的记录已被回滚移除;
- 在第三部分中,线程 B 在线程 A 的事务 2 进行期间插入了显示器:它是在事务之外进行的,因为事务是线程 A 的局部变量。事务 2 的回滚移除了 A 插入的键盘和鼠标,但没有移除 B 插入的显示器。这个结果是可重现的。
8.12.5. 结论
前面的示例展示了线程本地数据在事务管理中的价值。不应完全照搬它的写法,但它准确地描述了框架的工作方式:Spring 的事务管理([@Transactional] 注解)把事务和数据库连接放入 [ThreadLocal] 中,数据访问层查询它们,而代码本身无需操作事务;Hibernate 同样可以把工作会话与当前线程关联起来。我们将在第 11 章再回到这些工具。在新代码中,尤其是使用虚拟线程时,推荐用 *[ScopedValue]* 来传递这类上下文信息。
8.13. 延伸阅读
线程同步是一个充满挑战的领域。本章介绍了主要工具;若要深入了解:
在现代代码中,很少直接操作 [Thread] 对象。人们更倾向于使用执行器([ExecutorService])、用于计算的并行流,以及用于等待型处理的虚拟线程。下一章将介绍使用 [CompletableFuture] 类的异步编程,它允许你把后续处理链接到耗时操作(网络访问、数据库、文件)的完成上,而无需阻塞线程。尽管如此,本章涉及的概念依然至关重要:所有这些任务都在线程中运行,它们共享的数据必须使用同样的工具([synchronized]、锁、原子类、并发集合)来保护。