Skip to content

8. 执行线程

本章介绍在单个程序中同时执行多段代码:线程(执行线程)以及用于同步它们的工具。大约二十年前,大多数机器只有一个处理器,并行在很大程度上是由操作系统维持的一种假象。如今,即使是最基本的笔记本电脑也有多个核心:多个线程确实在同时运行,这使得这里讨论的同步问题更加普遍。

Kotlin 在 JVM 上没有自己的线程:它使用 Java 的线程,这些线程自 Java 第一个版本(1996 年)起就通过[Thread] 类、关键字[synchronized]以及[wait] 和[notify] 方法(来自[Object] 类)被集成到 Java 中。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])。JDK 框架中的所有这些类都可以在 Kotlin 中直接使用:这是它的主要优势之一。Kotlin 标准库在此基础上增加了一些函数,使它们用起来更方便:[thread] 函数、[withLock] 扩展函数(来自[kotlin.concurrent] 包)、[synchronized] 函数,以及[@Volatile] 和[@Synchronized] 注解……我们将在本章介绍所有这些工具。

不过,线程并不是 Kotlin 在并发编程方面的最终方案:它原生的异步解决方案是协程,将在第 9 章介绍。它们以线程为基础,而我们在这里要讲的一切(临界区、写入可见性、死锁等)对于完全理解它们仍然至关重要。

示例位于 Gradle 项目[08-threads]中。每个程序是位于以其命名的包中的一个文件([threads01/Threads01.kt] 位于包 [threads01] 中……),并通过[gradlew -q run -Pmain=threads01.Threads01Kt]执行,或者在 IntelliJ IDEA 中通过绿色三角形执行。任何程序参数都使用选项[--args]传递给 Gradle:[gradlew -q run -Pmain=threads08.Threads08Kt --args="5"]。

开始之前先提醒一点:多线程程序的结果每次运行都会有所不同。线程获得处理器访问权的顺序取决于操作系统、处理器数量和机器的负载。本章中重现的结果是在一台与其他高度活跃的程序共享的双处理器 Linux 机器上得到的。如果你运行这些示例,会得到相似的结果,但很少会完全相同。我们会在每种情况下指出哪些结果是可重现的,哪些不是。

8.1. Thread 类

应用程序启动时,它运行在一个称为线程的执行流中。对线程建模的类是 JDK 包中的[java.lang.Thread] 类。请回忆一下,Kotlin 把 Java 的访问器[getXxx()] / [setXxx(…)] (以及布尔值的[isXxx()] )表示为属性:我们写[thread.name = "Main"] 而不是[thread.setName("Main")]。该类的主要构造函数、属性和方法如下:

成员
作用
[Thread(task: Runnable)], [Thread(task: Runnable, name: String)]
创建一个线程,它将执行[run] 的[task] 方法。[Runnable] 是 Java 接口[void run()]:通过 SAM 转换(第 7 章),可以向它传入 lambda[{ … }] 或函数引用[::f]
[thread(start, isDaemon, name, …) { … }]
(Kotlin 库,包[kotlin.concurrent])创建一个执行该 lambda 的线程,用具名参数对其进行配置,并且默认会立即运行它
[Thread.ofPlatform()]、[Thread.ofVirtual()]
(Java 21)为平台线程或虚拟线程提供一个“构建器”,可以在创建线程之前对其进行配置(名称、守护线程等)
[Thread.currentThread()]
执行调用此方法的代码的线程
[name]
线程的名称(可修改的属性),便于跟踪
[threadId()]
(Java 19)线程的唯一数字标识符,类型为[Long];它取代了已弃用的[getId()]
[isDaemon]
指示(固定的)线程是否为守护线程(见下文)
[priority]
线程的优先级,范围从 1([MIN_PRIORITY])到 10([MAX_PRIORITY]),默认值为 5([NORM_PRIORITY])
[state]、[isAlive]
线程状态([NEW]、[RUNNABLE]、[BLOCKED]、[WAITING]、[TIMED_WAITING]、[TERMINATED]);[isAlive] 指示线程是否已启动且尚未结束(只读)
[isVirtual]
(Java 21)指示线程是否为虚拟线程(只读)
[start()]
启动线程
[join()]、[join(duration: Duration): Boolean]
正在执行 [T2.join()] 的线程 T1 会被阻塞,直到线程 T2 结束。第二种形式(Java 19)限制等待时间,并指示 T2 是否已结束
[Thread.sleep(ms: Long)]、[Thread.sleep(d: Duration)]
执行该方法的线程被挂起[ms] 毫秒(或持续时间[d])。它会让出 CPU,CPU 被交给另一个线程
[interrupt()]、[isInterrupted]
请求线程挂起;检查是否已请求挂起(见下文)

如果线程在等待期间被中断,方法[join] 和[sleep] 会抛出异常[InterruptedException]。在 Java 中,这是一个受检异常,编译器要求处理它,或者在[throws] 子句中声明它。Kotlin 没有受检异常(第 3 章):编译器不会强制要求任何事情。这并不意味着你可以忽略这个异常所表示的含义:我们将在线程中断一节中讨论这一点。

[Thread] 类还有一个方法[stop],它曾用于强制终止线程。该方法自 Java 1.2 起就已弃用,自 Java 20 起,它只是抛出[UnsupportedOperationException] 异常:突然停止线程可能会使它正在处理的数据处于不一致的状态。如今,我们是通过中断它,来请求线程协作式地停止:稍后我们会讲到这一点。

这是第一个演示主执行线程存在的应用程序——主执行线程就是执行函数[main]的那个线程。程序[Threads01.kt] 如下:

// 程序的主线程
package threads01

import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun main() {
    // 执行此代码的线程
    val main = Thread.currentThread()
    // Java 启动器为它指定了名称
    println("Name of the current thread: [${main.name}]")
    // 可以修改
    main.name = "Main"
    println("Name of the current thread: [${main.name}]")
    // 几个属性
    println("Identifier (threadId): ${main.threadId()}")
    println("Daemon thread (isDaemon): ${main.isDaemon}")
    println("Virtual thread (isVirtual): ${main.isVirtual}")
    println("Priority (priority): ${main.priority}")
    println("State (state): ${main.state}")
    println("Text representation: $main")
    println("Number of processors: ${Runtime.getRuntime().availableProcessors()}")

    // 每秒显示一次
    val format = DateTimeFormatter.ofPattern("HH:mm:ss")
    repeat(5) {
        println("${main.name} : ${LocalTime.now().format(format)}")
        // 线程挂起 1 秒
        Thread.sleep(1000)
    }
}

结果:

> gradlew -q run -Pmain=threads01.Threads01Kt
Name of the current thread: [main]
Name of the current thread: [Main]
Identifier (threadId): 3
Daemon thread (isDaemon): false
Virtual thread (isVirtual): false
Priority (priority): 5
State (state): RUNNABLE
Text representation: Thread[#3,Main,5,main]
Number of processors: 2
Main : 12:15:09
Main : 12:15:10
Main : 12:15:11
Main : 12:15:12
Main : 12:15:13

注释:

  • 第 9 行:获取对执行该程序的线程的引用;
  • 第 11–14 行:我们显示它的名称,修改它(对属性[name]的一次简单赋值,它会调用 Java 方法[setName]),然后再次显示它。最初,主线程的名称是[main] (结果的第 1 行):这是 Java 启动器赋予它的名称;
  • 第 15–22 行:线程的一些属性。在这次执行中,主线程的 ID 为 3:虚拟机在执行[main]之前会为自身的目的创建几个线程,这个 ID 可能因 Java 版本而异。它既不是守护线程([isDaemon] 等于[false]),也不是虚拟线程(我们稍后将讨论这两个概念);它的优先级是正常优先级 5;它当前正在运行([RUNNABLE])。线程的方法[toString]由模板["$main"] 调用(第 21 行),显示它的 ID、名称、优先级以及其线程组的名称([main]);
  • 第 22 行:运行该示例的机器有 2 个处理器;
  • 第 26–29 行:每秒打印一条消息的循环。[Thread.sleep(1000)] 使主线程挂起一秒钟。在 Java 中,函数[main] 必须在[InterruptedException] 子句中声明受检异常[throws];在 Kotlin 中则没有这种要求。请注意[HH:mm:ss] 格式(小时从 0 到 23):[hh] 格式则会显示 1 到 12 的小时。

8.2. 创建执行线程

可以编写这样的应用程序:其中的代码片段在不同的执行线程中“同时”执行。如果机器的处理器数量少于准备执行的线程数量,这些线程就共享处理器:每个线程轮流在短暂的时间内(几毫秒)获得处理器。在多处理器机器上,多个线程确实在同时执行。分配给线程的时间取决于各种因素,包括它的优先级,该优先级有一个默认值,但可以通过编程方式设置(属性[priority]);这只是一个指导性的参考,操作系统可以自由地忽略它(Linux 默认就会忽略它)。获得处理器访问权的线程可以提前释放它:

  • 通过等待某个事件(例如用[join]等待另一个线程完成,等待某个信号);
  • 通过进入睡眠状态一段指定的时间([sleep])。

首先创建线程 T,例如通过构造函数[Thread(task, name)],其中 [task] 是实现 Java 接口[Runnable]的对象,该接口唯一的方法是[void run()]。借助第 7 章中介绍的SAM 转换,可以传入类型为[() -> Unit] 的 lambda 或函数引用,而不是[Runnable]。在较旧的代码中,我们还会遇到派生自[Thread] 并重新定义其[run] 方法的类:不推荐这样做,因为它把要执行的任务与执行任务的手段混在了一起。

创建线程并不会启动它:

  • 线程 T 的执行由[T.start()]启动:传给 T 的构造函数的任务的[run] 方法随后将由线程 T 执行。执行[T.start()] 指令的代码不会等待线程 T 结束:它会立即转到下一条指令。现在我们有两个线程在并行运行。它们常常需要相互通信,以跟踪共同工作的进展:这就是线程同步问题;
  • 线程 T 一旦启动,就自主运行。当它正在执行的函数完成时,它就停止;
  • 我们可以使用[T.join()]等待它执行完毕。这是一条阻塞指令:执行它的线程会被阻塞,直到线程 T 完成其工作。这是一种基本的同步方法。

程序[Threads02.kt] 如下:

// 创建执行线程
package threads02

import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun main() {
    // 为主线程命名
    Thread.currentThread().name = "Main"

    // 创建 5 个线程
    val tasks = Array(5) { i ->
        // 第 i 号线程将执行 display 函数;它被命名为 "i"
        Thread(::display, i.toString())
    }
    // 启动它们的执行(非阻塞操作)
    for (task in tasks) {
        task.start()
    }

    // 主线程结束
    println("End of thread ${Thread.currentThread().name} at ${time()}")
}

// 线程所执行的函数:它具有 Runnable.run() 的形状
fun display() {
    // 执行该函数的线程
    val current = Thread.currentThread()
    println("Start of execution of the display function in thread ${current.name}" +
            " (id ${current.threadId()}) : ${time()}")
    // 休眠 1 秒
    sleep(1000)
    println("End of execution of the display function in thread ${current.name} : ${time()}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        // 休眠被中断:恢复线程的中断标志
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 9 行:为主线程指定一个名称;
  • 第 12–14 行:创建 5 个线程。函数[Array(5) { i -> … }] 创建一个包含 5 个元素的数组,其中第 i 个元素是 lambda 返回的值。因此线程引用被存储在数组中,以便稍后取用。每个线程执行第 26–33 行中的函数[display] ;
  • 第 14 行:类型为[::display]的函数引用[() -> Unit]被自动转换为[Runnable] 对象:函数[display] 没有参数,也不返回结果,与[run]一样。在 Java 中,在紧凑源文件里,你必须写成[this::display];在 Kotlin 中,[display] 是一个顶层函数,只需简单地写作[::display]。构造函数的第二个参数是线程名称;
  • 第 17–18 行:启动这些线程。此操作是非阻塞的:线程 #i 与启动它的主线程并行运行;
  • 第 22 行:主线程到达程序末尾;
  • 第 26–33 行:函数[display] 显示执行它的线程的名称和 ID,以及执行的开始和结束时间(精确到毫秒);
  • 第 32 行:任何执行函数[display] 的线程都会暂停 1 秒钟。处理器随后被交给另一个等待处理器的线程。在 1 秒钟的暂停结束时,暂停的线程重新具备获得处理器的资格。轮到它时,它就会获得处理器;
  • 第 37–42 行:函数[sleep] 封装了[Thread.sleep]。Kotlin 编译器不要求捕获[InterruptedException] 异常,该异常可能由[sleep] 抛出。然而,如果允许它从线程所执行的函数中逃逸,它会使该线程终止,并在控制台上输出一条错误消息。因此函数[sleep] 会捕获它,并重置线程的中断标志(第 42 行);我们将在中断一节中解释这一操作。赋给子句[_] 的参数的名称[catch] 表示该参数未被使用。我们在本章的大多数程序中都会遇到这个小函数;
  • 第 47 行:函数[time]以表达式([= …])的形式编写,按[HH:mm:ss.SSS] 格式返回当前时间([SSS]:毫秒)。

结果:

> gradlew -q run -Pmain=threads02.Threads02Kt
Start of execution of the display function in thread 3 (id 24) : 12:15:14.492
Start of execution of the display function in thread 4 (id 25) : 12:15:14.492
Start of execution of the display function in thread 0 (id 21) : 12:15:14.492
Start of execution of the display function in thread 1 (id 22) : 12:15:14.491
End of thread Main at 12:15:14.490
Start of execution of the display function in thread 2 (id 23) : 12:15:14.492
End of execution of the display function in thread 3 : 12:15:15.560
End of execution of the display function in thread 1 : 12:15:15.564
End of execution of the display function in thread 2 : 12:15:15.568
End of execution of the display function in thread 0 : 12:15:15.564
End of execution of the display function in thread 4 : 12:15:15.572

这些结果提供了很多信息:

  • 首先,我们可以看到启动线程是非阻塞的。主线程启动了 5 个线程,并在线程 2 尚未显示其第一条消息时就到达了程序末尾(第 5 行);
  • 线程的执行顺序是不可预测的:在这次运行中,线程 3 和 4 在线程 0 之前显示了它们的开始消息。这里操作系统有 6 个线程和 2 个处理器;它根据自己的规则把处理器分配给这些线程;
  • 我们还注意到,显示的顺序并不总是遵循所显示时间的顺序:主线程在 14.490 显示了它的结束,而在此之前已显示了时间为 14.491 和 14.492 的消息。时间是在输出之前计算的,在此期间,另一个线程可能已经向控制台写入了内容。[println] (它调用[System.out.println])是线程安全的:两个线程写入的两行不会混在一起,但它们的顺序无法保证;
  • 所创建线程的 ID(21 到 25)表明,虚拟机已经为自身的目的创建了大约二十个线程(垃圾回收、即时编译器等);
  • 每个线程用[sleep]暂停一秒钟,然后完成函数[display]的执行;
  • 最后,程序没有在主线程完成其工作时停止:虚拟机等待所有五个线程完成。这是因为这些线程不是守护线程:当 Java 虚拟机的所有非守护线程都结束时,它才会停止。

反过来,可以通过在启动线程之前把其属性从守护线程[isDaemon] 设置为[true] ,把它声明为守护线程。守护线程是不会阻止虚拟机停止的服务线程:当最后一个非守护线程结束时,它们就会被停止。程序[Threads03.kt] 使用 Kotlin 库中的[thread] 函数来创建它们:

// 守护线程 - kotlin.concurrent 的线程函数
package threads03

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread

fun main() {
    // 为主线程命名
    Thread.currentThread().name = "Main"

    // 创建并启动 5 个名为 0、1、2…… 的守护线程
    for (i in 0..<5) {
        // thread 创建一个线程,对其进行配置并(默认)立即启动
        thread(isDaemon = true, name = "$i") {
            display()
        }
    }

    // 给线程留出启动的时间
    sleep(100)
    // 主线程结束,因此程序也随之结束
    println("End of thread ${Thread.currentThread().name} at ${time()}")
}

// 线程所执行的函数
fun display() {
    val current = Thread.currentThread()
    println("Start of execution of the display function in thread ${current.name} : ${time()}")
    // 休眠 1 秒
    sleep(1000)
    println("End of execution of the display function in thread ${current.name} : ${time()}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 6 行:函数[thread] 属于标准库中的[kotlin.concurrent] 包;必须导入它;
  • 第 13–16 行:函数[thread(…) { … }] 创建一个线程,该线程将执行圆括号之后的 lambda 表达式(“尾随 lambda”的语法,第 7 章)。它的所有其他参数都有默认值;我们需要的参数通过具名实参设置:这里是[isDaemon = true] 和[name = "$i"]。它的签名如下:[fun thread(start: Boolean = true, isDaemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: () -> Unit): Thread]。默认情况下([start = true]),线程会被立即启动;函数返回所创建的线程。它是 Java 序列[var t = new Thread(…); t.setDaemon(true); t.start();]的有用替代品。区间[0..<5] (从 0 到 4 的整数)与[0 until 5]相同;
  • 第 21 行:主线程等待 100 毫秒,让这些线程有时间启动,然后终止。

结果:

1
2
3
4
5
6
7
> gradlew -q run -Pmain=threads03.Threads03Kt
Start of execution of the display function in thread 1 : 12:15:15.827
Start of execution of the display function in thread 2 : 12:15:15.817
Start of execution of the display function in thread 3 : 12:15:15.831
Start of execution of the display function in thread 0 : 12:15:15.832
Start of execution of the display function in thread 4 : 12:15:15.833
End of thread Main at 12:15:15.819

所有 5 个线程都开始了执行,然后主线程终止(第 6 行)。请注意,它的消息(时间为 15.819)显示在时间为 15.827 到 15.833 的消息之后:它在其他线程写入任何内容之前就已经计算了时间。随后,守护线程在其一秒钟的睡眠期间被停止:没有显示任何结束消息。在负载很重的机器上,有些线程甚至来不及显示它们的开始消息,因为 100 毫秒不足以让它们获得处理器:因此,再次运行可能会产生不同数量的开始消息,但绝不会有结束消息。用[main]结束[exitProcess(0)] (包[kotlin.system],它调用[System.exit(0)])也能达到同样的效果,它会关闭虚拟机,从而关闭应用程序的所有线程,无论是否为守护线程。我们稍后将讨论的虚拟线程始终是守护线程。

如果主线程想要等待它所创建的线程结束,它就使用[join] 方法。[Threads04.kt] 程序还展示了如何让线程执行带参数的函数:

// 用 join 等待线程结束 - 用 lambda 创建的线程
package threads04

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread

fun main() {
    // 为主线程命名
    Thread.currentThread().name = "Main"

    // 创建并启动 5 个线程
    val tasks = (0..<5).map { i ->
        // 线程执行该 lambda,lambda 以带类型的参数调用 display
        thread(name = "$i") { display(i, 1000L + 100 * i) }
    }

    // 我们等待所有线程结束
    for (task in tasks) {
        // 主线程被阻塞,直到线程 [task] 结束
        task.join()
    }
    // 主线程结束
    println("End of thread ${Thread.currentThread().name} at ${time()}")
}

// 线程所执行的函数
fun display(number: Int, duration: Long) {
    val name = Thread.currentThread().name
    println("Start of execution of task $number in thread $name : ${time()}")
    // 休眠 [duration] 毫秒
    sleep(duration)
    println("End of execution of task $number in thread $name : ${time()}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 13–15 行:函数[map] 把区间[0..<5] 转换为由函数[thread]创建并启动的 5 个线程的列表。[tasks] 的类型是[List<Thread>];
  • 第 15 行:线程执行 lambda[{ display(i, 1000L + 100 * i) }]。这种语法允许调用带类型化参数的函数(在本例中是一个[Int] 和一个[Long]),而[run] 没有参数;
  • 该 lambda 直接使用参数 [i],它来自 lambda [map]。在 Java 中,它必须使用循环变量的副本([int number = i;]),因为 Java 的 lambda 只能使用实际上是 final 的变量,而[i] 这个[for (int i = 0; …; i++)] 的循环变量会被修改。在 Kotlin 中,这里不会出现这个问题:[i] 是参数,因此是不可变的,循环变量[for (i in 0..<5)]也是如此,它在每次迭代中都是一个新的[val] 变量。Kotlin 还允许 lambda 捕获[var] 变量并修改它(第 7 章);但是,在多个线程之间共享的[var] 变量会引发并发访问问题,我们稍后将研究。我们所避免的陷阱是一个经典的陷阱:较晚启动的线程不得读取后续迭代中[i] 的值;
  • 第 19–21 行:主线程等待每一个线程。它首先被阻塞,等待线程 0,然后等待线程 1,依此类推。当它退出循环时,它所启动的 5 个线程都已完成;
  • 第 32 行:任务 i 睡眠 1,000 + 100 × i 毫秒,因此这些线程会按已知的顺序终止。

结果:

> gradlew -q run -Pmain=threads04.Threads04Kt
Start of execution of task 2 in thread 2 : 12:15:16.127
Start of execution of task 4 in thread 4 : 12:15:16.119
Start of execution of task 0 in thread 0 : 12:15:16.130
Start of execution of task 3 in thread 3 : 12:15:16.120
Start of execution of task 1 in thread 1 : 12:15:16.118
End of execution of task 0 in thread 0 : 12:15:17.130
End of execution of task 1 in thread 1 : 12:15:17.232
End of execution of task 2 in thread 2 : 12:15:17.329
End of execution of task 3 in thread 3 : 12:15:17.430
End of execution of task 4 in thread 4 : 12:15:17.535
End of thread Main at 12:15:17.535

开始消息以任意顺序出现,但结束消息按数字顺序出现,因为睡眠时长是递增的:结果的这一部分是可重现的。最后一行表明,主线程在它所启动的线程之后结束,也就是在最后一个线程结束的那一刻。

8.3. 停止线程:中断

如何在线程完成工作之前停止它,例如当用户取消一个耗时很长的操作时?JVM 不允许你杀死线程;它提供了一种称为中断的协作机制:

  • 每个线程都有一个中断标志,这是一个最初设置为[false]的布尔值;
  • 一个名为 T1 的线程如果想终止线程 T2,就调用[T2.interrupt()]。这会设置 T2 的终止标志。这是一个终止请求:T2 并没有被终止;由该线程自己决定何时以及如何终止自己,以便使其数据保持一致的状态;
  • 如果 T2 阻塞在某个等待方法中([sleep]、[join]、[wait],以及[java.util.concurrent] 中的大多数阻塞方法),它就会被唤醒:该方法抛出[InterruptedException] 异常,并且中断标志被重置为[false];
  • 如果 T2 执行计算而从不等待,它就必须定期使用[Thread.currentThread().isInterrupted] 检查自己的标志。

在 Java 中,阻塞方法声明了受控异常[InterruptedException]:编译器要求程序员决定如何处理停止请求。Kotlin 不要求这样做,但这个决定仍然需要做出,而且是同一个决定。有两种正确的响应方式:让异常向调用方传播,或者拦截它并干净地结束任务。当这两种方式都不可行时,如程序[sleep] 的函数[Threads02.kt]中那样,就通过[Thread.currentThread().interrupt()] 重置标志,使调用代码仍然能看到该请求。唯一不正确的响应是忽略该异常。程序[Threads05.kt] 演示了这三种情况:

// 停止线程:中断
package threads05

import java.time.Duration
import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun main() {
    // 1 - 大部分时间处于休眠的线程
    val sleeper = Thread.ofPlatform().name("sleeper").start {
        var round = 0
        try {
            while (true) {
                round++
                println("${time()} : sleeper, round $round")
                // 如果线程在休眠时被中断,sleep 会抛出 InterruptedException
                Thread.sleep(400)
            }
        } catch (_: InterruptedException) {
            // 中断是一个停止请求:线程干净地完成其工作
            println("${time()} : sleeper interrupted while sleeping, it stops")
        }
    }
    // 2 - 从不休眠、一直在计算的线程
    val calculator = Thread.ofPlatform().name("calculator").start {
        var n = 0L
        // 线程定期检查其中断标志
        while (!Thread.currentThread().isInterrupted) {
            n++
        }
        println("${time()} : calculator interrupted after %,d iterations, it stops".format(n))
    }
    // 3 - 忽略中断的线程(不要效仿)
    val deaf = Thread.ofPlatform().name("deaf").daemon().start {
        repeat(10) {
            try {
                Thread.sleep(400)
            } catch (_: InterruptedException) {
                // 异常被"吞掉"了:停止请求丢失
                println("${time()} : deaf ignores the interruption and continues")
            }
        }
    }

    // 让线程工作 1 秒
    Thread.sleep(1000)
    println("${time()} : Main requests the three threads to stop")
    sleeper.interrupt()
    calculator.interrupt()
    deaf.interrupt()
    // 等待每个线程结束,最多 1 秒
    for (thread in listOf(sleeper, calculator, deaf)) {
        val finished = thread.join(Duration.ofSeconds(1))
        println("${time()} : thread ${thread.name} finished: $finished")
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 10–21 行:线程[sleeper] 由平台线程构造器[Thread.ofPlatform().name("sleeper")]创建并启动,其方法[start] 接收要执行的 lambda(我们将在程序[Threads06.kt]中介绍这些构造器)。它的大部分时间都花在[Thread.sleep]中。循环[while (true)] 没有终止条件:使循环退出的是当线程被中断时由[InterruptedException]抛出的异常[sleep] (第 19 行)。该 lambda 是一个包含线程全部工作的[try] 语句:收到该异常后,线程显示一条消息,然后终止;
  • 第 25–31 行:线程[calculator] 从不等待。它在每次循环迭代时检查自己的中断标志(第 28 行)。Java 方法[isInterrupted()] 在 Kotlin 中被视为布尔属性[isInterrupted]。迭代次数由 Kotlin 字符串函数[format]显示,该函数使用[String.format]的格式:[%,d] 使用当前语言的千位分隔符显示整数;
  • 第 34–40 行:[deaf] 线程拦截了[InterruptedException] ,并像什么都没发生一样继续运行。停止请求丢失了:这就是要避免的错误。它是一个守护线程([daemon()]),这样程序无需等待它就可以终止;
  • 第 46 行:主线程让其他线程运行一秒钟;
  • 第 48–50 行:它请求这三个线程停止;
  • 第 52–54 行:它等待每个线程结束,最多等待一秒钟。如果线程在该时间内已结束,方法[join(Duration)] (Java 19)返回[true] ,否则返回[false]。[Duration.ofSeconds(1)] 表示一秒钟的持续时间(类[java.time.Duration])。

结果:

> gradlew -q run -Pmain=threads05.Threads05Kt
12:15:17.883 : sleeper, round 1
12:15:18.367 : sleeper, round 2
12:15:18.666 : Main requests the three threads to stop
12:15:18.671 : sleeper interrupted while sleeping, it stops
12:15:18.680 : deaf ignores the interruption and continues
12:15:18.682 : calculator interrupted after 856,531,345 iterations, it stops
12:15:18.713 : thread sleeper finished: true
12:15:18.718 : thread calculator finished: true
12:15:19.719 : thread deaf finished: false

线程[sleeper] 和 [calculator] 在请求之后几毫秒就终止了;线程[deaf] 忽略了请求,一秒钟后仍未结束([false],最后一行)。calculator 的迭代次数每次运行都差别很大,取决于它分配到的 CPU 时间份额;其余结果是可重现的,第 4 到 6 行在数量级上是一致的。

中断是整个 Java 库用来关闭操作的机制:稍后我们将看到,任务([cancel] 方法的[Future])以及线程池的突然关闭([shutdownNow])都会中断受影响的线程。第 9 章讨论的协程有它们自己的机制——取消,它同样是协作式的——以及其他停止进程的方式,例如超时。

8.4. 虚拟线程

到目前为止我们创建的线程都是平台线程:每个线程都是对一个操作系统线程的封装,并在其整个生命周期内占用该操作系统线程。操作系统线程是一种昂贵的资源:创建它需要时间,它的栈会预留内存(大约一兆字节),而且系统无法高效地管理超过几千个这样的线程。然而,为每个客户端专门分配一个线程的服务器(见下一段中的图示)大部分时间都在等待:等待数据库的响应、客户端的下一个请求……在这些等待期间,系统线程被阻塞而无法使用。

Java 21 引入了虚拟线程 (JEP 444),可以在 Kotlin 中原样使用。虚拟线程与任何其他线程一样是一个[Thread] 对象,但它由 Java 虚拟机而不是操作系统管理:

  • 为了执行,虚拟线程被挂载到一个平台线程上,称为它的“载体线程”。载体线程组成一个小型线程池,其大小默认等于处理器的数量;
  • 当虚拟线程阻塞时([sleep]、等待网络 I/O、锁、阻塞队列等),它会被卸载:它的栈被放到虚拟机的内存中,载体线程立即可用于另一个虚拟线程。当等待结束时,虚拟线程被重新附加到某个宿主线程上——不一定是同一个线程;
  • 一个虚拟线程只占用几百字节:可以创建数百万个。

Kotlin 协程(第 9 章)基于类似的思想——挂起正在等待的进程而不阻塞系统线程——但它是由 Kotlin 编译器而不是虚拟机实现的。我们将在第 9 章比较这两种方法。

程序[Threads06.kt] 比较了启动 10,000 个平台线程和 10,000 个虚拟线程的情况,每个线程睡眠一秒钟:

// 平台线程和虚拟线程(Java 21)
package threads06

fun main() {
    val nbThreads = 10_000
    // 两个线程构建器
    measure("platform threads", Thread.ofPlatform(), nbThreads)
    measure("virtual threads", Thread.ofVirtual(), nbThreads)

    // 虚拟线程运行在称为载体线程的平台线程上
    val virtual = Thread.ofVirtual().name("virtual").start {
        println("Before sleep: ${Thread.currentThread()}")
        sleep(100)
        println("After sleep: ${Thread.currentThread()}")
    }
    virtual.join()
    println("isVirtual: ${virtual.isVirtual}, isDaemon: ${virtual.isDaemon}")
}

// 启动 [nbThreads] 个休眠 1 秒的线程,等待它们结束并显示总耗时
fun measure(kind: String, builder: Thread.Builder, nbThreads: Int) {
    val start = System.nanoTime()
    val threads = List(nbThreads) { builder.start { sleep(1000) } }
    threads.forEach { it.join() }
    val duration = (System.nanoTime() - start) / 1_000_000
    println("%,d %s slept 1 s each: total duration %,d ms".format(nbThreads, kind, duration))
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

注释:

  • 第 7–8 行:函数[measure] 被调用两次——先使用平台线程构造器([Thread.ofPlatform()]),然后使用虚拟线程构造器([Thread.ofVirtual()])。两个构造器共享公共类型[Thread.Builder];其余代码完全相同。构造器通过链式调用进行配置:[name("virtual")] 设置线程名称;[name("", 0)] 会请求以前缀后跟从 0 开始的编号来命名线程;[daemon()] (仅限平台线程)请求守护线程。它的方法[start(Runnable)] 创建线程并立即启动它;它的方法[unstarted(Runnable)] 创建线程但不启动它;
  • 第 21–26 行:函数[measure] 启动[nbThreads] 个睡眠一秒钟的线程,等待它们结束,并显示总耗时。函数[List(n) { … }] 构造由[builder.start { … }] (被转换为[Runnable]的 lambda)创建并启动的线程列表。[System.nanoTime()] 方法返回以纳秒为单位的时间,它仅用于测量持续时间;
  • 第 11–14 行:一个名为[virtual] 的虚拟线程在睡眠前后显示其文本表示;
  • 第 17 行:虚拟线程始终是守护线程。

结果:

1
2
3
4
5
6
> gradlew -q run -Pmain=threads06.Threads06Kt
10,000 platform threads slept 1 s each: total duration 4,272 ms
10,000 virtual threads slept 1 s each: total duration 1,296 ms
Before sleep: VirtualThread[#20026,virtual]/runnable@ForkJoinPool-1-worker-2
After sleep: VirtualThread[#20026,virtual]/runnable@ForkJoinPool-1-worker-1
isVirtual: true, isDaemon: true
  • 10,000 个平台线程花了好几秒才完成本应只需一秒的工作:创建系统线程和管理它们的栈代价很高。如果是 100,000 个线程,程序很可能会因内存不足或可用系统线程不足而失败;
  • 10,000 个虚拟线程只用了一秒多一点就完成了同样的任务:休眠期间,它们不占用任何系统线程。确切的时间每次运行都会有所不同,但这两类线程之间的差异是可重现的;
  • 虚拟线程的文本表示([VirtualThread[#…,virtual]])在字符[@]之后指明了它所挂载的载体线程:来自[ForkJoinPool-1] 池的一个线程,我们稍后将回过头来讨论它。在这次执行中,虚拟线程在载体[worker-2] 上进入睡眠,并在载体[worker-1]上恢复执行:它确实被卸载,然后重新挂载到另一个载体上(这取决于具体执行情况)。

虚拟线程并不会让计算更快:一个让处理器一直忙碌而从不等待的计算,在虚拟线程中并不比在平台线程中运行得更快,并发计算的数量仍然受处理器数量的限制。它们的好处在于,可以不计成本地为每个大部分时间都在等待的任务专门分配一个线程:服务器就是这种情况,下一段以及第 12 章和第 13 章也是如此。我们将要介绍的有关线程同步的所有内容,同样适用于虚拟线程和平台线程。

8.5. 线程的用途

现在我们已经强调了默认线程的存在——即执行[main] 函数的线程——并且知道了如何创建额外的线程,下面让我们更仔细地看看线程的好处。它们有两个主要用途:

  • 为一次耗时的计算利用机器的所有处理器:工作被划分为若干部分,分配给不同的线程。我们将在本章末尾使用并行流和[Fork/Join] 网格来做到这一点;
  • 同时执行多个任务,特别是当其中一些任务主要涉及等待(等待网络响应、磁盘读取或用户输入)时。客户端/服务器互联网应用程序就是这种情况,我们将在第 12 章介绍。

在客户端/服务器互联网应用程序中,位于机器 S1 上的服务器响应来自位于远程机器 C1、C2、……、Cn 上的客户端的请求:

Image

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

Image

使用平台线程时,服务器实际上使用的是线程池——稍后讨论——其有限的线程数量限制了同时服务的客户端数量。使用虚拟线程时,上述方案再次成为最优解决方案:每个客户端一个虚拟线程,即使有数万个客户端也是如此,因为等待中的客户端不占用任何系统线程。这正是 Tomcat 等 JVM Web 服务器如今所支持的——我们将在第 13 章使用它。在 Kotlin 中,第 9 章介绍的协程为同一问题提供了另一种解决方案:每个客户端一个协程。

8.6. 线程之间交换信息

在前面的示例中,线程执行的是不带参数的函数,或者是调用带参数函数的 lambda。由于[run] 方法(属于[Runnable] )既没有参数也没有返回值,因此是 lambda 向启动的线程传递信息:它捕获所需的变量。如果被捕获的变量引用的是一个对象,被启动的线程还可以在其中存储结果,供启动它的线程读取。程序[Threads07.kt] 如下:

// 线程之间交换信息
package threads07

import java.time.Duration
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread

// 启动线程与被启动线程之间交换的信息
class Data(
    // 由启动线程设置
    val start: LocalTime,
    val duration: Int,
) {
    // 由被启动线程设置
    lateinit var end: LocalTime
}

fun main() {
    // 为主线程命名
    Thread.currentThread().name = "Main"

    // 创建并启动 5 个线程
    val data = mutableListOf<Data>()
    val tasks = mutableListOf<Thread>()
    for (i in 0..<5) {
        // 与线程交换的对象:启动线程设置开始时间和持续时间
        val d = Data(LocalTime.now(), i + 1)
        data += d
        // 被启动线程通过捕获该对象的 lambda 接收它
        tasks += thread(name = "$i") { sleep(d) }
    }

    // 我们依次等待各个线程
    val format = DateTimeFormatter.ofPattern("HH:mm:ss")
    for ((task, d) in tasks.zip(data)) {
        // 等待线程结束
        task.join()
        // 线程已填写其对象的结束时间
        val actualDuration = Duration.between(d.start, d.end).toMillis() / 1000.0
        println("Thread %s finished: start %s, scheduled duration %d s, end %s, actual duration %.3f s"
            .format(task.name, d.start.format(format), d.duration, d.end.format(format), actualDuration))
    }
    // 主线程结束
    println("End of thread ${Thread.currentThread().name} at ${LocalTime.now().format(format)}")
}

// 线程所执行的函数
fun sleep(data: Data) {
    try {
        // 休眠 [duration] 秒
        Thread.sleep(data.duration * 1000L)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
    // 被启动线程向启动线程返回一个结果
    data.end = LocalTime.now()
}

注释:

  • 第 10–16 行:与每个线程交换的信息是一个[Data] 对象。启动线程和被启动线程之间存在双向的信息交换。[start] 和 [duration] 是在主构造函数中声明的[val] 属性:它们在对象构造时一次性设置:
    • [start]:线程的执行开始时间,由启动线程设置;
    • [duration]:被启动线程的睡眠时长(以秒为单位),由启动线程设置;
    • [end]:线程的执行结束时间,由被启动线程设置。这是一个[lateinit var] 属性(第 4 章):对象构造时它没有值,但它的类型并不是[LocalTime?]。在赋值之前读取它会抛出[UninitializedPropertyAccessException] 异常。对应的 Java 类将近有三十行,包括它的访问器;
  • 第 28–29 行:创建一个 [Data] 对象并将其添加到 [data] 列表中;
  • 第 31 行:lambda[{ sleep(d) }] 捕获变量[d]:被启动的线程将执行第 49–57 行的函数[sleep] ,并以对象[d] 作为参数。运算符[+=] 把函数[thread] 返回的线程添加到可修改的列表[tasks]中;
  • 第 36–42 行:主线程等待它启动的每个线程结束,然后从线程中取出[Data] 对象 并显示其内容。函数[zip] 把这两个列表合并为一个由二元组组成的列表([Pair<Thread, Data>]),循环[for] 把它解构为[(task, d)]。实际持续时间由[Duration.between(d.start, d.end)]计算;
  • 第 52 行:参数的[duration] 属性设置睡眠时长;
  • 第 57 行:参数的[end] 属性被填充。

结果:

1
2
3
4
5
6
7
> gradlew -q run -Pmain=threads07.Threads07Kt
Thread 0 finished: start 12:15:25, scheduled duration 1 s, end 12:15:26, actual duration 1.014 s
Thread 1 finished: start 12:15:25, scheduled duration 2 s, end 12:15:27, actual duration 2.000 s
Thread 2 finished: start 12:15:25, scheduled duration 3 s, end 12:15:28, actual duration 3.001 s
Thread 3 finished: start 12:15:25, scheduled duration 4 s, end 12:15:29, actual duration 4.001 s
Thread 4 finished: start 12:15:25, scheduled duration 5 s, end 12:15:30, actual duration 5.004 s
End of thread Main at 12:15:30

这个示例表明,两个线程可以交换信息:

  • 调用线程可以通过向被调用线程提供信息来控制其执行;
  • 被启动的线程可以向启动它的线程返回结果。

为了让启动线程知道它所期待的结果何时可用,必须在被启动线程结束时通知它。这里,它使用[join] 方法等待线程结束。这不仅仅是时机的问题:我们将在有关[@Volatile] 注解的一节中看到,一个线程执行的写操作不一定对另一个线程可见。适用于任何由 JVM 执行的程序——因此也适用于 Kotlin 程序——的 Java 内存模型保证:一个线程写入的所有内容,对使用[join]等待它结束的线程都是可见的,并且调用线程在[start] 之前写入的所有内容,对被调用线程也是可见的。我们稍后将探讨其他同步方式。

我们也可以不用 lambda,而是编写一个实现[Runnable] 的类,其属性包含所交换的信息。lambda 更简洁;它是如今最常见的写法。为了获取处理操作的结果,我们稍后还将介绍[Callable<V>] 接口,其[call()] 方法返回一个结果,以及在第 9 章中介绍协程的[async] 函数,它返回一个延迟结果([Deferred])。

8.7. 并发访问共享资源

8.7.1. 不同步的并发访问

在前面一段中,信息只是在两个线程之间、在非常特定的时刻交换的:这是参数传递的一个经典例子。还有其他情况,信息由多个线程共享,这些线程可能希望同时读取或更新它。这就提出了该信息的完整性问题。假设共享的信息是一个包含各种信息 I1、I2、……、In 的结构 S:

  • 线程 T1 开始更新结构 S:它修改了字段 I1,并在完成对结构 S 的完整更新之前被中断;
  • 获得处理器的线程 T2 随后读取结构 S 以做出决策。它读取的是处于不稳定状态的结构:有些字段是最新的,有些则不是。

这种情况称为对共享资源(这里是结构 S)的并发访问。它往往难以管理。让我们考虑下面的示例,来说明可能出现的问题:

  • 应用程序将生成 n 个线程,其中 n 作为参数传入;
  • 共享资源是一个计数器,必须由每个生成的线程对其进行递增;
  • 在应用程序结束时,显示计数器的值。因此它应该等于 n。

程序[Threads08.kt] 如下:

// 对共享资源的非同步并发访问
package threads08

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.system.exitProcess

// 共享资源
object Counter {
    // 线程计数器,由所有线程共享;只能在对象内部修改
    var value = 0
        private set

    // 每个线程所执行的函数
    fun increment() {
        val name = Thread.currentThread().name
        // 读取计数器
        val v = value
        println("At ${time()}, thread $name read the counter value: $v")
        // 等待:线程让出处理器
        sleep(1000)
        // 递增计数器
        value = v + 1
        println("At ${time()}, thread $name wrote the counter value: $value")
    }
}

fun main(args: Array<String>) {
    // 检查参数:要创建的线程数
    val nbMaxThreads = 100
    val nbThreads = args.singleOrNull()?.toIntOrNull() ?: -1
    if (nbThreads !in 1..nbMaxThreads) {
        System.err.println("syntax: threads08.Threads08Kt nbThreads (nbThreads between 1 and $nbMaxThreads)")
        exitProcess(1)
    }

    // 创建并启动线程
    val threads = List(nbThreads) { i -> Thread(Counter::increment, "$i") }
    threads.forEach { it.start() }
    // 等待线程结束
    threads.forEach { it.join() }
    // 显示计数器
    println("Number of threads generated: ${Counter.value}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 9–24 行:共享资源是单例对象[value] 的属性[Counter] (声明[object],第 4 章)。计数器被封装在这个对象中,函数[increment] 由每个线程执行。关键字[private set] (第 12 行)使该属性可以从任何地方读取,但只能在对象内部修改:这相当于 Java 版本中的私有字段及其访问器[getValue] ;
  • 第 18 行:读取计数器;
  • 第 21 行:线程暂停 1 秒钟。因此它失去了 CPU;
  • 第 23 行:计数器递增;
  • 第 30–34 行:线程数量作为实参传入。表达式[args.singleOrNull()?.toIntOrNull() ?: -1] 返回程序的唯一参数所包含的整数,如果参数不是恰好一个([singleOrNull] 此时返回[null])或者该参数不是整数([toIntOrNull] 此时返回[null]),则返回 -1。因此,条件[nbThreads !in 1..nbMaxThreads] 既会拒绝缺失或无效的参数,也会拒绝区间 [1, 100] 之外的数字。在 Java 中,必须编写一个方法来拦截[NumberFormatException]。出错时,程序向错误输出([System.err])写入一条消息,并以退出码 1 终止([exitProcess(1)],来自[kotlin.system] 包);
  • 第 38 行:每个线程执行对象[increment] 的函数[Counter],通过绑定引用[Counter::increment]来指代;
  • 第 39–41 行:启动这些线程,然后主线程等待它们结束。

加入这一秒钟的暂停,仅仅是为了迫使线程在读取和写入计数器之间让出 CPU。在实际中,无法保证线程不会在这两个时刻之间被中断,而且在多处理器机器上,两个线程甚至可能在完全相同的时刻读取计数器。这一秒钟的睡眠只是把这种风险具体化了。

使用 Gradle 时,程序参数通过[--args] 选项传递。没有任何参数时,会显示一条错误消息(Linux shell 中的[echo $?] 命令显示最后执行的程序的退出码;在 Windows 上则是[echo %errorlevel%])。为了确保显示的是程序的退出码——而不是 Gradle 的退出码(它还会报告[run] 任务失败)——我们在这里使用[java] 命令直接运行了编译后的类:

1
2
3
4
> java -cp … threads08.Threads08Kt
syntax: threads08.Threads08Kt nbThreads (nbThreads between 1 and 100)
> echo $?
1

使用 5 个线程:

> gradlew -q run -Pmain=threads08.Threads08Kt --args="5"
At 12:15:31.799, thread 3 read the counter value: 0
At 12:15:31.799, thread 0 read the counter value: 0
At 12:15:31.800, thread 2 read the counter value: 0
At 12:15:31.799, thread 4 read the counter value: 0
At 12:15:31.789, thread 1 read the counter value: 0
At 12:15:32.820, thread 3 wrote the counter value: 1
At 12:15:32.831, thread 0 wrote the counter value: 1
At 12:15:32.835, thread 4 wrote the counter value: 1
At 12:15:32.835, thread 2 wrote the counter value: 1
At 12:15:32.863, thread 1 wrote the counter value: 1
Number of threads generated: 1

看这些结果,发生的事情一目了然:

  • 第一个线程读取计数器。它读到 0。它暂停 1 秒钟,从而失去了 CPU;
  • 第二个线程也读取计数器的值。它读到的仍然是 0,因为前一个线程尚未对其递增。它也暂停 1 秒钟;
  • 不到一秒钟,所有 5 个线程都有时间读到值 0;
  • 当它们醒来时,它们对自己读到的值 0 进行递增,并且都向计数器写入值 1,最后一行(第 11 行)证实了这一点。这个错误的结果是可重现的:每次执行之间只有线程的顺序会发生变化。

有人可能会反对说这个示例是人为设计的。那么让我们去掉睡眠,并使用运算符[++],它给人一种单条指令的错觉。程序[Threads09.kt] 如下:

// 没有 sleep 时更新丢失:counter++ 不是原子操作
package threads09

// 共享资源
object Counter {
    var value = 0
}

fun main(args: Array<String>) {
    // 参数:线程数、每个线程的递增次数
    val nbThreads = args.getOrNull(0)?.toInt() ?: 4
    val nbIncrements = args.getOrNull(1)?.toInt() ?: 50_000_000

    // 实验重复三次
    for (trial in 1..3) {
        Counter.value = 0
        // 创建并启动线程
        val threads = List(nbThreads) {
            Thread.ofPlatform().start {
                repeat(nbIncrements) {
                    // 读取、递增、写入:三个操作
                    Counter.value++
                }
            }
        }
        // 等待线程结束
        threads.forEach { it.join() }
        // 结果
        val expected = nbThreads * nbIncrements
        println("Trial %d: expected value %,d, value obtained %,d, lost updates %,d"
            .format(trial, expected, Counter.value, expected - Counter.value))
    }
}

注释:

  • 第 11–12 行:线程数量(默认为 4)以及每个线程执行的递增次数(默认为 5000 万)可以作为参数传入。[args.getOrNull(0)] 返回第一个参数,如果它不存在则返回[null] :随后由 Elvis 运算符[?:] 提供默认值。分隔符[_]使常量[50_000_000] 易于阅读;
  • 第 19 行:线程由[Thread.ofPlatform().start { … }]创建并启动;它们不需要名称。函数[List(nbThreads) { … }] 把创建的线程收集到一个列表中;
  • 第 22 行:每个线程不暂停地递增共享计数器;
  • 第 30–31 行:在格式字符串中,[%,d] 使用当前语言的千位分隔符显示整数(在这里是英语:逗号)。

结果:

1
2
3
4
> gradlew -q run -Pmain=threads09.Threads09Kt
Trial 1: expected value 200,000,000, value obtained 148,585,966, lost updates 51,414,034
Trial 2: expected value 200,000,000, value obtained 200,000,000, lost updates 0
Trial 3: expected value 200,000,000, value obtained 200,000,000, lost updates 0

在第一次测试中丢失了数千万次更新。高级操作[Counter.value++] 实际上会被翻译成几条基本的处理器指令:从内存中读取值,在寄存器中递增它,并把结果写回内存。如果两个线程在其中一个线程写入自己的值之前读取了同一个值,就会丢失一次递增,与前面的示例完全一样。

测试 2 和 3 需要解释一下:它们得出了精确的值。最可能的解释如下:经过一定的执行时间后,虚拟机的即时编译器(JIT)优化了循环[repeat(nbIncrements) { … }] (这是一个[inline]函数,Kotlin 编译器已把它替换为一个简单的循环):它判定在循环期间不应有其他线程访问计数器(代码中没有任何内容要求这一点),于是把计数器放入处理器寄存器中。随后每个线程读取一次计数器,在其寄存器中给它加上 5000 万,并在最后写回一次。如果各线程的工作没有重叠——这里就是这种情况——结果就是正确的;反之,如果四个线程在任何一个写入之前都读取了值 0,那么四个结果中有三个会丢失——也就是一次丢失 1.5 亿次更新。在这次运行中,只有第一个测试——它在这一优化之前基本已经执行完——丢失了更新;在其他运行中,测试 2 和 3 也可能丢失更新,有时一次丢失 1.5 亿次。这正是这类错误如此危险的原因:程序可以运行数月,然后恰恰在机器负载更重或运行更快的那一天出错。

问题从何而来?一个线程读取了过时的值,因为另一个线程在完成更新计数器的任务之前被中断了,或者正在另一个处理器上同时工作。这就引出了程序中的临界资源和临界区的概念:

  • 临界资源 是一次只能被一个线程持有的资源。这里的临界资源是计数器;
  • 程序的临界区 是线程执行流中的一段指令序列,线程在其间访问临界资源。我们必须确保,在这个临界区内,该线程是唯一能访问该资源的线程。

在程序[Threads08.kt]中,临界区是读取计数器与写入其新值之间的代码:

1
2
3
4
5
6
7
        // 读取计数器
        val v = value
        println("At ${time()}, thread $name read the counter value: $v")
        // 等待:线程让出处理器
        sleep(1000)
        // 递增计数器
        value = v + 1

要执行这段代码,必须保证线程是唯一正在运行的线程。它可以被中断,但在中断期间,不能有其他线程执行同一段代码。JVM 提供了各种工具来确保单线程进入代码的临界区,而 Kotlin 提供了一些函数使它们用起来更方便。我们现在来看其中的几个。

8.7.2. synchronized 函数和 @Synchronized 注解

在 Java 中,[synchronized] 块按如下方式界定临界区:[synchronized (lock) { …critical section… }]。[lock] 是对所有执行临界区的线程可见的对象。在 JVM 上,每个对象都有一个内部锁,也称为监视器。[synchronized] 块确保一次只有一个线程持有对象 [lock]的监视器,这意味着一次只有一个线程执行临界区:遇到被另一个线程持有的监视器的线程会被阻塞,直到该监视器被释放。无论是正常退出还是因异常退出,监视器都会在退出该块时被释放。

Kotlin 没有[synchronized] 关键字。取而代之的是,它的标准库提供了一个[synchronized] 函数,其签名为[inline fun <R> synchronized(lock: Any, block: () -> R): R]。得益于尾随 lambda 的语法,对它的调用[synchronized(lock) { …critical section… }] 的写法与 Java 块完全一样。由于该函数是[inline],Kotlin 编译器会用 lambda 的函数体替换该调用,并用与 JVM 相同的指令把它包围起来,就像 Java 块一样([monitorenter] / [monitorexit]):执行上没有任何差别。该函数返回 lambda 的值,这使我们可以写出[val v = synchronized(lock) { counter }]。

前面的示例在[Threads10.kt]中被改写如下:

// 由 synchronized 块保护的临界区
package threads10

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.system.exitProcess

// 共享资源
object Counter {
    // 线程计数器
    private var counter = 0
    // 同步对象,对所有线程可见
    private val lock = Any()

    // 计数器的值,在锁的保护下读取
    val value: Int
        get() = synchronized(lock) { counter }

    // 每个线程所执行的函数
    fun increment() {
        val name = Thread.currentThread().name
        println("At ${time()}, thread $name is waiting for permission to enter the critical section")
        // 同一时间只有一个线程执行下面的块
        synchronized(lock) {
            // 读取计数器
            val v = counter
            println("At ${time()}, thread $name read the counter value: $v")
            // 等待:线程让出处理器但保留锁
            sleep(1000)
            // 递增计数器
            counter = v + 1
            println("At ${time()}, thread $name wrote the counter value: $counter")
        }
        println("At ${time()}, thread $name left the critical section")
    }
}

fun main(args: Array<String>) {
    // 检查参数:要创建的线程数
    val nbMaxThreads = 100
    val nbThreads = args.singleOrNull()?.toIntOrNull() ?: -1
    if (nbThreads !in 1..nbMaxThreads) {
        System.err.println("syntax: threads10.Threads10Kt nbThreads (nbThreads between 1 and $nbMaxThreads)")
        exitProcess(1)
    }

    // 创建并启动线程
    val threads = List(nbThreads) { i -> Thread(Counter::increment, "$i") }
    threads.forEach { it.start() }
    // 按线程创建的相反顺序等待线程结束
    Thread.currentThread().name = "Main"
    for (thread in threads.asReversed()) {
        println("At ${time()}, thread Main is waiting for the end of thread ${thread.name}")
        thread.join()
        println("At ${time()}, thread Main was notified of the end of thread ${thread.name}")
    }
    // 显示计数器
    println("Number of threads generated: ${Counter.value}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 13 行:[lock] 是使所有线程能够同步的对象。它只有这一个用途:它是[Any] 类的一个简单对象,该类是 Kotlin 类的根(相当于[Object])。它是一个[val] 属性:该引用绝不能改变,否则两个线程可能会锁定两个不同的对象。它是私有的:[Counter] 对象之外的任何代码都无法获取这个锁;
  • 第 11 行:计数器现在是一个私有属性;只能通过属性[value]从外部访问它;
  • 第 16–17 行:属性[value] 没有字段:它的访问器[get] 在锁的保护下读取计数器,并返回函数[synchronized]返回的值,即来自 lambda[{ counter }]的值。在这里,这并非严格必要,因为主线程已经使用[join]等待其他线程结束;但这是一个好习惯:受锁保护的数据必须在该锁的保护下读取和写入;
  • 第 24–32 行:函数[increment] 的临界区被对函数[synchronized]的调用所包围。线程在睡眠一秒钟期间一直持有锁:其他线程无法进入;
  • 第 52–55 行:主线程按照线程创建的相反顺序等待它们。函数[asReversed] 返回按相反顺序遍历的列表的视图 ,而不复制它。

使用 3 个线程的结果:

> gradlew -q run -Pmain=threads10.Threads10Kt --args="3"
At 12:16:51.163, thread 2 is waiting for permission to enter the critical section
At 12:16:51.163, thread Main is waiting for the end of thread 2
At 12:16:51.165, thread 1 is waiting for permission to enter the critical section
At 12:16:51.157, thread 0 is waiting for permission to enter the critical section
At 12:16:51.170, thread 2 read the counter value: 0
At 12:16:52.181, thread 2 wrote the counter value: 1
At 12:16:52.182, thread 1 read the counter value: 1
At 12:16:52.182, thread 2 left the critical section
At 12:16:52.182, thread Main was notified of the end of thread 2
At 12:16:52.182, thread Main is waiting for the end of thread 1
At 12:16:53.182, thread 1 wrote the counter value: 2
At 12:16:53.182, thread 0 read the counter value: 2
At 12:16:53.182, thread 1 left the critical section
At 12:16:53.183, thread Main was notified of the end of thread 1
At 12:16:53.183, thread Main is waiting for the end of thread 0
At 12:16:54.183, thread 0 wrote the counter value: 3
At 12:16:54.183, thread 0 left the critical section
At 12:16:54.183, thread Main was notified of the end of thread 0
Number of threads generated: 3
  • 三个线程几乎在同一时间请求进入临界区;
  • 只有一个线程进入——这里是线程 2(进入的顺序无法保证:不一定是最先到达的线程最先进入)。它读取计数器,睡眠一秒钟,写入新值,然后退出临界区;
  • 另外两个线程被阻塞,直到第一个线程退出临界区,然后一个接一个地继续执行。每个线程读取的是前一个线程写入的值。请注意(第 7–8 行),线程 1 在线程 2 表示它已退出临界区之前就读取了计数器:线程 2 确实释放了锁,但它直到[synchronized] 块之后才显示其消息,而线程 1 更快;
  • 主线程一直在等待线程 2 结束。当收到线程 2 已结束的通知时,它等待线程 1 结束,然后等待线程 0 结束;
  • 线程数量是正确的(最后一行)。无论线程以何种顺序运行,这个结果都是可重现的。

在 Java 中,关键字[synchronized] 也可以用来标注整个方法。Kotlin 为此提供了注解[@Synchronized] (包[kotlin.jvm],自动导入):[@Synchronized fun m() { … }] 会生成一个 Java[synchronized] 方法,它等价于一个包含整个函数体的[synchronized(this) { … }] 调用。在诸如[object] 的[Counter] 中,被锁定的对象就是单例对象本身。我们将在程序[Threads17.kt]中使用它。这是最短的语法。但它有一个缺点:被锁定的对象从外部是可见的,外部代码可以获取同一个锁并阻塞我们的代码。因此,通常更好的做法是锁定一个私有 对象,如示例中所示。出于同样的原因,你永远不应锁定字符串(相同的字符串字面量是在整个程序中使用的同一个共享对象)。在数字方面,Kotlin 比 Java 更进一步:锁定一个 *[Int]*——它会被转换为共享的 *[Integer]* 对象——会产生编译错误(***[error: synchronizing on 'Int' is forbidden.]***),而 Java 对于“基于值”的类的对象只会发出警告。

已经持有某个监视器的线程可以重新进入同一对象上的[synchronized] 块而不会阻塞自己:这种锁被称为可重入的。因此,一个[@Synchronized] 函数可以调用同一对象上的另一个[@Synchronized] 函数。

8.7.3. ReentrantLock 类

[synchronized] 锁简单但死板:在监视器上等待的线程会无限期地等待,既不能在一定时间后放弃,也不能被中断。[java.util.concurrent.locks.ReentrantLock] 类(Java 5)是一种显式锁——同样是可重入的——它提供了这些能力。它实现了[Lock] 接口。我们将使用下列构造函数和方法:

成员
作用
[ReentrantLock()]、[ReentrantLock(fair: Boolean)]
创建一个锁。公平锁([true])按线程请求它的顺序授予线程;非公平锁(默认)更快,但线程可能插队
[lock()]
正在执行[V.lock()]的线程 T1 请求锁 V。如果 V 没有被任何线程持有,它就被授予 T1。如果线程 T2 随后执行同样的操作,它会被阻塞:一个锁只能属于一个线程。当 T1 释放 V 时,T2 将被解除阻塞。因此,可能有多个线程在等待 V 时被阻塞
[tryLock(): Boolean]、[tryLock(time: Long, unit: TimeUnit): Boolean]
立即请求锁,或者最多等待[time]的时间来请求锁。如果未能获取锁,该方法返回[false]
[lockInterruptibly()]
类似于[lock],但等待可以被中断([InterruptedException])
[unlock()]
持有 V 的线程释放它。随后,等待 V 的线程之一获得它
[isHeldByCurrentThread]
指示当前线程是否持有该锁
[newCondition(): Condition]
创建一个与该锁关联的条件(见下文)
[withLock { … }]
(Kotlin 库,包[kotlin.concurrent])[Lock] 接口的扩展函数:在持有锁的情况下执行 lambda,并在结束时释放它,无论是否发生异常

在 Java 中,同步临界区总是遵循同样的模式:[V.lock(); try { …critical section… } finally { V.unlock(); }]。重要的是不要忘记释放锁;否则,等待该锁的线程将一直被无限期阻塞。这就是为什么锁要在[finally] 块中释放,无论是否发生异常,该块都会被执行。*[synchronized] 块会自动完成这一点;而使用 *[ReentrantLock]* 时,则需要由程序员自己来做。Kotlin 可以写出完全相同的代码,但它的标准库提供了更好的解决方案:扩展函数[withLock]*,它一劳永逸地应用了这种模式。它的定义大致如下:

1
2
3
4
5
6
7
8
public inline fun <T> Lock.withLock(action: () -> T): T {
    lock()
    try {
        return action()
    } finally {
        unlock()
    }
}

这是[inline] 函数:对[lock.withLock { … }] 的调用在编译时会被替换为模式[lock] / [try] / [finally] / [unlock],没有任何额外开销,并且不可能再遗漏[unlock]。这与[use] 函数的处理方式相同,后者用来替代针对 Java 资源的[try] 语句(第 3 章)。程序[Threads11.kt] 用[ReentrantLock]改写了前面的示例:

// 由 ReentrantLock 保护的临界区
package threads11

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.system.exitProcess

// 共享资源
object Counter {
    // 线程计数器
    private var counter = 0
    // 同步对象:一个公平锁(true)
    private val lock = ReentrantLock(true)

    // 计数器的值,在锁的保护下读取
    val value: Int
        get() = lock.withLock { counter }

    // 每个线程所执行的函数
    fun increment() {
        val name = Thread.currentThread().name
        println("At ${time()}, thread $name is waiting for permission to enter the critical section")
        // 请求获取锁;withLock 在离开块时释放锁,无论是否发生异常
        lock.withLock {
            // 读取计数器
            val v = counter
            println("At ${time()}, thread $name read the counter value: $v")
            // 等待
            sleep(1000)
            // 递增计数器
            counter = v + 1
            println("At ${time()}, thread $name wrote the counter value: $counter")
            println("At ${time()}, thread $name leaves the critical section")
        }
    }
}

fun main(args: Array<String>) {
    // 检查参数:要创建的线程数
    val nbMaxThreads = 100
    val nbThreads = args.singleOrNull()?.toIntOrNull() ?: -1
    if (nbThreads !in 1..nbMaxThreads) {
        System.err.println("syntax: threads11.Threads11Kt nbThreads (nbThreads between 1 and $nbMaxThreads)")
        exitProcess(1)
    }

    // 创建并启动线程
    val threads = List(nbThreads) { i -> Thread(Counter::increment, "$i") }
    threads.forEach { it.start() }
    // 等待线程结束
    threads.forEach { it.join() }
    // 显示计数器
    println("Number of threads generated: ${Counter.value}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

主程序与[Threads08.kt]的相同。注释:

  • 第 15 行:线程同步对象现在是一个公平锁,即[ReentrantLock];
  • 第 7 行:扩展函数[withLock] 必须被导入;
  • 第 26 行:临界区的开始。线程被阻塞,直到锁被释放;
  • 第 26–35 行:由于锁必须始终被释放,无论是否发生异常,因此临界区是传给 *[withLock]* 的 lambda,它在退出 lambda 时释放锁。消息“离开临界区”是在临界区内显示的最后一条消息;
  • 第 18–19 行:同样的处理方式保护了对计数器的读取。[withLock] 返回其 lambda 的值:访问器返回的值是在持有锁的情况下读取的。Java 版本为了这个简单的读取操作,不得不写七行[try] / [finally] 代码。

结果:

> gradlew -q run -Pmain=threads11.Threads11Kt --args="3"
At 12:16:54.619, thread 2 is waiting for permission to enter the critical section
At 12:16:54.607, thread 0 is waiting for permission to enter the critical section
At 12:16:54.608, thread 1 is waiting for permission to enter the critical section
At 12:16:54.647, thread 2 read the counter value: 0
At 12:16:55.671, thread 2 wrote the counter value: 1
At 12:16:55.672, thread 2 leaves the critical section
At 12:16:55.699, thread 0 read the counter value: 1
At 12:16:56.700, thread 0 wrote the counter value: 2
At 12:16:56.700, thread 0 leaves the critical section
At 12:16:56.700, thread 1 read the counter value: 2
At 12:16:57.701, thread 1 wrote the counter value: 3
At 12:16:57.701, thread 1 leaves the critical section
Number of threads generated: 3

结果与前面的相似:线程逐个通过临界区,最终的计数是正确的。由于锁是公平的,线程是按照它们请求锁的顺序获得锁的:即它们调用[lock] 的顺序,而“等待许可”消息的时间——是稍早计算的——只能近似反映这一顺序(这里,线程 2 显示的时间最晚,但它最先调用了[lock] )。

什么时候应该使用[ReentrantLock] 而不是[synchronized]?当你需要它的某个附加功能时:超时([tryLock],我们将用它来避免死锁)、可中断的等待、公平性或多个条件。否则,[synchronized] 函数就工作得很好;借助[withLock],Kotlin 使这两种工具用起来同样简单和安全。自 Java 24 起,[synchronized] 不再给虚拟线程带来问题:此前,在[synchronized] 块中阻塞的虚拟线程无法释放其宿主线程,这使得[ReentrantLock] 成为首选。

8.7.4. 进程同步:文件锁

前面的锁在同一个虚拟机内——也就是在同一个进程内——同步线程。有时不同的进程需要共享某个资源,例如文件,或者你可能想防止同一个应用程序的两个实例被启动。JVM 没有提供在进程之间共享的具名同步对象;为此,要使用由操作系统管理的文件锁 :即[java.nio.channels.FileLock] 类。锁是在已打开的文件上以[FileChannel] 通道的形式获得的:

  • [lock(): FileLock]:等待锁变为可用并获取它;
  • [tryLock(): FileLock?]:尝试不等待地获取锁,如果锁被另一个进程持有,则返回[null] 。Kotlin 把这个 Java 方法的返回值视为平台类型([FileLock!]);程序员需要把它当作可能为[null]来处理;
  • [release()]:释放锁。当通道关闭或进程结束时,锁也会被释放,即使进程是被突然终止的:锁不会“成为孤儿”。类[FileLock] 实现了接口[AutoCloseable]:它的方法[close] 调用[release],因此 Kotlin 函数[use] 可以释放该锁。

程序[Threads12.kt] 在两个不同的进程中被启动两次,这两个进程共享一个临界区:

// 文件锁可以同步不同的进程
package threads12

import java.nio.channels.FileChannel
import java.nio.file.Path
import java.nio.file.StandardOpenOption.CREATE
import java.nio.file.StandardOpenOption.WRITE
import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun main(args: Array<String>) {
    // 被锁定的文件为所有使用它的进程所知
    val file = Path.of(System.getProperty("java.io.tmpdir"), "kotlin-course-threads-12.lock")
    // 进程名称作为参数传入
    val process = args.firstOrNull() ?: "P"

    // 打开文件(如果文件尚不存在则创建)
    FileChannel.open(file, CREATE, WRITE).use { channel ->
        println("${time()} : process $process requests the lock")
        // 不等待的尝试:如果其他进程持有锁则返回 null
        val lock = channel.tryLock() ?: run {
            println("${time()} : the lock is held by another process, $process waits")
            // 无时间限制地等待
            channel.lock()
        }
        // use 在块结束时释放锁(close 会调用 release)
        lock.use {
            // 进程之间的临界区
            println("${time()} : process $process obtained the lock, it works for 3 s")
            Thread.sleep(3000)
            println("${time()} : process $process releases the lock")
        }
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 13 行:用作锁的文件。所有锁定该文件的进程彼此同步。它被放在系统的临时文件夹中,该文件夹由系统属性[java.io.tmpdir] 指定(在 Linux 上为[/tmp] )。它的内容无关紧要:可以保持为空;
  • 第 18 行:文件以写入方式打开(独占锁需要这样),并且如果尚不存在则创建([CREATE])。枚举[StandardOpenOption] 中的常量已被逐个导入(第 6–7 行)。函数[use] 将在最后关闭通道;
  • 第 21–24 行:该进程尝试不等待地获取锁。如果失败([tryLock] 返回[null]),Elvis 运算符[?:] 就执行块[run],它发出这一信号,然后无限期地等待锁:该块的值——由[lock]返回的锁——成为变量[lock]的值。因此,该变量是非空类型;
  • 第 27–31 行:临界区,持续 3 秒钟,随后由函数[use]释放锁。

文件锁属于整个进程,而不属于单个线程:它不用于同步同一进程内的线程(在同一进程内对同一文件的两次加锁请求会触发[OverlappingFileLockException] 异常)。我们启动进程 A,等待 1.5 秒,然后在第二个终端中启动进程 B。进程 A 的结果:

1
2
3
4
> gradlew -q run -Pmain=threads12.Threads12Kt --args="A"
12:16:58.028 : process A requests the lock
12:16:58.040 : process A obtained the lock, it works for 3 s
12:17:01.041 : process A releases the lock

进程 B 的结果:

1
2
3
4
5
> gradlew -q run -Pmain=threads12.Threads12Kt --args="B"
12:16:59.552 : process B requests the lock
12:16:59.604 : the lock is held by another process, B waits
12:17:01.060 : process B obtained the lock, it works for 3 s
12:17:04.064 : process B releases the lock

进程 B 检测到锁被进程 A 持有,于是进行了等待。它在 A 释放锁几毫秒之后获得了锁。这一机制的一个常见用途是防止同一个应用程序的两个实例被启动:第二个实例无法用[tryLock]获取锁,就会立即终止。

8.7.5. 屏障:Semaphore 类

信号量 是针对许可 (或名额)的计数器。[java.util.concurrent.Semaphore] 类提供了以下方法:

成员
作用
[Semaphore(permits: Int)], [Semaphore(permits: Int, fair: Boolean)]
创建一个具有[permits] 个许可的信号量;第二个参数的含义与[ReentrantLock] 相同
[acquire()]
获取一个许可。如果没有剩余许可,线程会被阻塞,直到有许可被释放。等待可以被中断([InterruptedException])
[acquireUninterruptibly()]
与上面相同,但等待不能被中断
[tryAcquire(): Boolean]、[tryAcquire(timeout: Long, unit: TimeUnit): Boolean]
不等待地获取许可,或者最多等待[timeout];失败时返回[false]
[release()]
归还(添加)一个许可;等待中的线程之一随后可以获取它
[availablePermits()]
可用许可的数量

与锁不同,许可不属于任何特定的线程:任何线程都可以调用[release],即使它从未获取过许可。因此,用零个许可创建的信号量是一道关闭的屏障,调用[acquire] 的线程会在它这里被阻塞。当时机到来时,另一个线程会通过调用[release]来打开它。这个时机完全取决于要解决的问题。获取了唯一许可的线程穿过了屏障,屏障在它身后关闭;通过归还许可,它为另一个线程打开了屏障。如果在前面的示例中,我们用这样的屏障替换锁,代码就变成下面这样([Threads13.kt]):

// 由屏障保护的临界区:只有一个许可的信号量
package threads13

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.Semaphore
import kotlin.system.exitProcess

// 共享资源
object Counter {
    // 线程计数器
    var value = 0
        private set
    // 屏障:一个创建时没有任何许可的信号量,因此处于关闭状态
    val sync = Semaphore(0)

    // 每个线程所执行的函数
    fun increment() {
        val name = Thread.currentThread().name
        println("At ${time()}, thread $name is waiting for permission to enter the critical section")
        // 通过屏障:线程取走唯一的许可,屏障在其身后关闭
        sync.acquireUninterruptibly()
        try {
            // 读取计数器
            val v = value
            println("At ${time()}, thread $name read the counter value: $v")
            // 等待
            sleep(1000)
            // 递增计数器
            value = v + 1
            println("At ${time()}, thread $name wrote the counter value: $value")
        } finally {
            // 许可被归还:屏障为另一个线程打开
            println("At ${time()}, thread $name leaves the critical section")
            sync.release()
        }
    }
}

fun main(args: Array<String>) {
    // 检查参数:要创建的线程数
    val nbMaxThreads = 100
    val nbThreads = args.singleOrNull()?.toIntOrNull() ?: -1
    if (nbThreads !in 1..nbMaxThreads) {
        System.err.println("syntax: threads13.Threads13Kt nbThreads (nbThreads between 1 and $nbMaxThreads)")
        exitProcess(1)
    }

    // 创建并启动线程
    val threads = List(nbThreads) { i -> Thread(Counter::increment, "$i") }
    threads.forEach { it.start() }
    // 让线程到达关闭的屏障
    Thread.sleep(500)
    // 打开临界区的屏障
    Thread.currentThread().name = "Main"
    println("At ${time()}, thread Main opens the barrier of the critical section")
    Counter.sync.release()
    // 等待线程结束
    threads.forEach { it.join() }
    // 显示计数器
    println("Number of threads generated: ${Counter.value}")
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 15 行:屏障被创建为关闭状态。它将由主线程在第 57 行打开;
  • 第 53 行:主线程等待半秒钟,以便让这些线程到达屏障;
  • 第 22 行:负责递增计数器的线程请求进入临界区的许可。各个线程在关闭的屏障前积聚。当主线程打开它时,等待中的线程之一通过,然后屏障再次关闭。方法[acquireUninterruptibly] 使线程在这段等待期间对中断没有反应;
  • 第 23–35 行:临界区被包含在 *[try] 中,其 *[finally]* 子句释放锁。Kotlin 标准库没有针对 Java 信号量的 *[withLock] 等价物:我们像在 Java 中那样写出模式[try] / [finally] (不过,协程库有它自己的信号量,带有函数[withPermit],我们将在第 9 章介绍);
  • 第 35 行:线程完成工作后,重新打开屏障,允许另一个线程进入。

结果:

> gradlew -q run -Pmain=threads13.Threads13Kt --args="3"
At 12:17:04.442, thread 1 is waiting for permission to enter the critical section
At 12:17:04.463, thread 0 is waiting for permission to enter the critical section
At 12:17:04.503, thread 2 is waiting for permission to enter the critical section
At 12:17:04.807, thread Main opens the barrier of the critical section
At 12:17:04.812, thread 0 read the counter value: 0
At 12:17:05.818, thread 0 wrote the counter value: 1
At 12:17:05.819, thread 0 leaves the critical section
At 12:17:05.820, thread 1 read the counter value: 1
At 12:17:06.821, thread 1 wrote the counter value: 2
At 12:17:06.821, thread 1 leaves the critical section
At 12:17:06.821, thread 2 read the counter value: 2
At 12:17:07.822, thread 2 wrote the counter value: 3
At 12:17:07.822, thread 2 leaves the critical section
Number of threads generated: 3

结果与前面的相似。我们可以看到,三个线程在屏障处等待,直到主线程把它打开(第 4 行)。

8.7.6. CountDownLatch 和 Semaphore 类

同步工具的另外两种用法是对前面示例的补充。

[java.util.concurrent.CountDownLatch] 对象是一个计数器:它以初始值 N 创建;每次调用它的[countDown] 方法都会使其递减;它的[await] 方法会阻塞调用线程,直到计数器达到 0。一旦达到 0,它就保持在 0:屏障永久打开,允许所有线程通过。当 N = 1 时,它充当赛跑的“发令信号”;当 N = 任务数量时,它是一种等待 N 个任务完成的方式,每个任务在完成时调用[countDown] 。程序[Threads14.kt] 如下:

// CountDownLatch:一个释放所有等待线程的启动信号
package threads14

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.CountDownLatch
import kotlin.concurrent.thread

fun main() {
    // 启动信号:从 1 开始的倒计时
    val start = CountDownLatch(1)

    // 创建并启动 4 个线程
    val threads = List(4) { i ->
        thread(name = "$i") {
            val name = Thread.currentThread().name
            println("${time()} : runner $name is waiting for the start signal")
            try {
                // 等待倒计时到达 0
                start.await()
                println("${time()} : runner $name has started")
            } catch (_: InterruptedException) {
                println("${time()} : runner $name gave up")
            }
        }
    }

    // 主线程等待 1 秒,然后发出启动信号
    Thread.sleep(1000)
    println("${time()} : start signal")
    // 倒计时到达 0:所有等待的线程被释放
    start.countDown()
    // 等待线程结束
    threads.forEach { it.join() }
    println("Value of the countdown: ${start.count}")
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 11 行:倒计时从 1 开始:闸门是关闭的;
  • 第 14–15 行:4 个线程(赛跑者)由函数[thread]创建并启动,并由函数[List(4) { i -> … }]添加到列表中;
  • 第 20 行:每个线程等待倒计时到达 0。方法[await] 可能抛出[InterruptedException];如果线程在等待期间被中断,它就退出比赛(第 23 行);
  • 第 32 行:主线程在一秒钟之后递减倒计时器;它到达 0;
  • 第 35 行:属性[count] (即 Java 方法[getCount()])返回倒计时器的当前值。

结果:

> gradlew -q run -Pmain=threads14.Threads14Kt
12:17:08.372 : runner 1 is waiting for the start signal
12:17:08.363 : runner 3 is waiting for the start signal
12:17:08.384 : runner 2 is waiting for the start signal
12:17:08.363 : runner 0 is waiting for the start signal
12:17:09.275 : start signal
12:17:09.300 : runner 1 has started
12:17:09.301 : runner 3 has started
12:17:09.301 : runner 2 has started
12:17:09.302 : runner 0 has started
Value of the countdown: 0

四名赛跑者在发令信号之后一起出发,彼此相差不过几毫秒。[CountDownLatch] 只能使用一次;[CyclicBarrier] 类提供可重复使用的集合点(N 个线程相互等待,然后一起出发),而[Phaser] 类则对这两种工具进行了推广。

让我们回到信号量最常见的用法:具有 N 个许可的信号量一次最多允许 N 个线程进入某个代码段。这对于限制对数量有限的资源(数据库连接、对服务器的并发请求等)的访问很有用。程序[Threads15.kt] 如下:

// Semaphore:一段代码中同时最多有 N 个线程
package threads15

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.Semaphore
import kotlin.concurrent.thread

fun main() {
    // 一个有 2 个许可(2 个名额)的信号量
    val semaphore = Semaphore(2)

    // 创建并启动 5 个线程
    val threads = List(5) { i ->
        thread(name = "$i") {
            val name = Thread.currentThread().name
            println("${time()} : thread $name is waiting for a place")
            // 请求一个名额:如果没有剩余名额则阻塞
            semaphore.acquireUninterruptibly()
            try {
                println("${time()} : thread $name obtained a place" +
                        " (free places: ${semaphore.availablePermits()})")
                // 工作
                sleep(1000)
            } finally {
                // 名额被归还
                println("${time()} : thread $name releases its place")
                semaphore.release()
            }
        }
    }
    // 等待线程结束
    threads.forEach { it.join() }
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 11 行:信号量有 2 个许可:2 个名额;
  • 第 19 行:线程请求一个名额。如果有可用的名额,它就拿走并继续;否则,它会被阻塞,直到有名额可用;
  • 第 22 行:仍然可用的名额数量;
  • 第 28 行:线程在[finally] 子句中归还它的名额。

结果:

> gradlew -q run -Pmain=threads15.Threads15Kt
12:17:09.754 : thread 4 is waiting for a place
12:17:09.755 : thread 3 is waiting for a place
12:17:09.791 : thread 3 obtained a place (free places: 0)
12:17:09.770 : thread 2 is waiting for a place
12:17:09.784 : thread 0 is waiting for a place
12:17:09.764 : thread 1 is waiting for a place
12:17:09.786 : thread 4 obtained a place (free places: 1)
12:17:10.798 : thread 3 releases its place
12:17:10.803 : thread 2 obtained a place (free places: 0)
12:17:10.805 : thread 4 releases its place
12:17:10.805 : thread 0 obtained a place (free places: 0)
12:17:11.831 : thread 0 releases its place
12:17:11.831 : thread 1 obtained a place (free places: 0)
12:17:11.831 : thread 2 releases its place
12:17:12.831 : thread 1 releases its place

所有五个线程都请求名额;其中两个立即获得(这里是线程 3 和 4),而另外三个在等待。每当一个线程释放它的名额,就有一个等待中的线程获得它。代码段中从来不会有超过两个线程。请注意,线程 3 在线程 4 显示“空闲名额:1”之前显示了“空闲名额:0”:线程 4 先获得名额并先读取了空闲名额数,但线程 3 显示其消息更快。单许可信号量的作用相当于锁,如程序[Threads13.kt]中那样。对于虚拟线程,信号量是限制并发的天然工具:我们不限制线程数量,而是为每个任务创建一个虚拟线程,并使用信号量来限制同时使用稀缺资源的任务数量。我们将在第 9 章用协程做同样的事情。

8.7.7. 写入可见性:@Volatile 注解

锁不仅仅用于使一组操作不可分割。它们还解决第二个更隐蔽的问题:写入的可见性。为了加快速度,处理器把值存储在它的寄存器和缓存中,而编译器会即时重新排序或消除读写操作,正如我们在程序[Threads09.kt]中所看到的。结果是,一个线程写入的值可能要过一段时间才会被另一个线程看到,或者也许永远看不到。

Java 内存模型管辖着由 JVM 执行的所有程序——包括 Kotlin 程序——它精确地定义了写入在何时保证可见:当写入与读取之间存在“先行发生”(happens-before)关系时。其中主要的几种如下:

  • 线程在释放锁之前所做的一切([synchronized] 块的结束、[unlock])对随后获取该锁的线程都是可见的;
  • 调用线程在[start] 之前所做的一切对被调用线程是可见的;一个线程所做的一切,对通过[join]等待它结束的线程是可见的;
  • 对[volatile] 字段的写入对该字段随后的任何读取都是可见的;
  • [java.util.concurrent] 中的工具提供类似的保证:一个线程在[release()]、[countDown()]、或向并发集合插入元素之前所做的一切,对随后执行[acquire()]、[await()]、或取出该元素的线程是可见的。

当这些关系都不存在时,就称程序包含“数据竞争”,此时没有任何保证。在 Java 中,字段是通过关键字[volatile] 声明的;Kotlin 没有这个关键字,但它有一个注解,即[@Volatile],应用于[var] 属性:这时存储该属性的字段就是一个 Java[volatile] 字段。程序[Threads16.kt] 在一个常见场景中演示了它的用处:用来指示线程停止的标志。

// 线程之间写入的可见性:@Volatile 注解
package threads16

import java.time.Duration
import java.time.LocalTime
import java.time.format.DateTimeFormatter

// 停止标志,由线程共享
object Flags {
    // 一个普通属性:线程可能永远看不到新值
    var stop = false
    // 一个 volatile 属性:任何写入对随后的读取都是可见的
    @Volatile
    var volatileStop = false
}

fun main() {
    // 1 - 停止标志是一个普通属性
    val t1 = Thread.ofPlatform().name("T1").daemon().start {
        var rounds = 0L
        while (!Flags.stop) {
            rounds++
        }
        println("${time()} : T1 saw the stop request after %,d rounds".format(rounds))
    }
    // 2 - 停止标志是一个 volatile 属性
    val t2 = Thread.ofPlatform().name("T2").daemon().start {
        var rounds = 0L
        while (!Flags.volatileStop) {
            rounds++
        }
        println("${time()} : T2 saw the stop request after %,d rounds".format(rounds))
    }

    // 让线程运行一秒钟
    Thread.sleep(1000)
    println("${time()} : Main requests T1 and T2 to stop")
    Flags.stop = true
    Flags.volatileStop = true
    // 等待两个线程结束,每个最多 2 秒
    for (thread in listOf(t2, t1)) {
        val finished = thread.join(Duration.ofSeconds(2))
        println("${time()} : ${thread.name} finished: $finished")
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 9–14 行:这两个标志,它们是单例对象[Flags]的属性。注解[@Volatile] (第 13 行,自动导入)指定,对属性[volatileStop] 的任何读取都必须从内存中读取,对它的任何写入都必须立即执行。属性 [stop] 是普通属性;
  • 第 19–24 行:只要普通属性[Flags.stop] 等于[false],线程 T1 就一直运行;
  • 第 27–32 行:线程 T2 对 volatile 属性[Flags.volatileStop]做同样的事情;
  • 第 38–39 行:一秒钟后,主线程把两个标志都设置为[true];
  • 第 41–43 行:它对这两个线程中的每一个最多等待 2 秒钟。两个线程都是守护线程,因此即使其中一个仍在运行,程序也可以终止。

结果:

1
2
3
4
5
> gradlew -q run -Pmain=threads16.Threads16Kt
12:18:56.183 : Main requests T1 and T2 to stop
12:18:56.214 : T2 saw the stop request after 468,368,999 rounds
12:18:56.340 : T2 finished: true
12:18:58.360 : T1 finished: false

线程 T2 立即收到了停止请求。而线程 T1 则始终没有收到:两秒钟后它仍在运行,直到虚拟机关闭才停止。即时编译器注意到循环[while (!Flags.stop) { rounds++ }] 不会修改 [stop] ,并且没有任何同步要求再次读取它,于是只在循环之前读取了一次这个字段:循环因此变成了无限循环。对属性 [stop] 的访问是通过它的访问器[getStop]完成的,但这没有任何区别:即时编译器用对字段的读取替换了对访问器的调用。这种行为在这里使用的 HotSpot 虚拟机上是可重现的,但并不受保证:另一种虚拟机或另一个版本可能会让 T1 停止。这恰恰就是问题所在:没有先行发生关系,程序的行为就是未定义的。

注解[@Volatile] 保证可见性,但不保证原子性:对[value++] [@Volatile] 属性执行它仍然是一次读取后跟一次写入,两个线程仍然可能丢失更新。[@Volatile] 因此适用于由一个线程写入、其他线程读取的标志,但不适用于共享计数器。要停止线程,上面描述的中断实际上比标志更可取:它还能唤醒阻塞在等待中的线程。

8.7.8. 原子类

[java.util.concurrent.atomic] 包(Java 5)提供了一些类,使对变量的简单操作成为原子的:操作由线程完整地执行,而没有任何其他线程能够在操作中途观察或修改该变量。前面的工具([synchronized]、[ReentrantLock]、[Semaphore])都是为了使一组操作成为原子的而设计的,代价是阻塞其他线程。对于简单但频繁的操作,原子类通过使用特殊的处理器指令避免了这种阻塞。[AtomicInteger] 类的主要方法如下:

方法
作用
[get(): Int]、[set(v: Int)]
读取和写入值(具有[volatile] 字段的语义)
[incrementAndGet(): Int]、[decrementAndGet(): Int]
把值递增(递减)1 并返回新值
[getAndIncrement(): Int]、[getAndDecrement(): Int]
与上面相同,但返回先前的值(如[x++] 和[x--])
[addAndGet(delta: Int): Int]
把[delta] 加到值上并返回新值
[getAndSet(v: Int): Int]
赋值[v] 并返回旧值
[compareAndSet(expected: Int, new: Int): Boolean]
仅当值为 [expected] 时才赋值 [new];如果赋值发生了则返回[true]
[updateAndGet(f: IntUnaryOperator): Int]
以原子方式把值 v 替换为 f(v) 并返回新值;在 Kotlin 中,向它传入的是 lambda:[a.updateAndGet { it * 2 }]

该包还提供[AtomicLong]、[AtomicBoolean]、[AtomicReference<V>] (对象的原子引用)以及原子数组([AtomicIntegerArray]……)。[LongAdder] 类(Java 8)是为多个线程非常频繁地更新而设计的计数器:它不使用所有线程竞争的单个变量,而是把递增分散到多个单元中,只有在请求总数时才对它们求和([sum])。

Kotlin 2.4 标准库也有自己的原子类,适用于所有 Kotlin 平台([AtomicInt]、[AtomicLong]、[AtomicReference]……来自[kotlin.concurrent.atomics] 包),但它们仍处于实验阶段:编译器要求显式选择启用([@OptIn(ExperimentalAtomicApi::class)])。因此,对于 JVM,我们使用 JDK 中的原子类。

程序[Threads17.kt] 以程序[Threads09.kt] 的结果为基础,比较了六种递增共享计数器的方式:

// 原子类:无锁操作
package threads17

import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.LongAdder
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

// 共享资源
object Counter {
    // @Volatile 保证写入的可见性,而不保证 value++ 的原子性
    @Volatile
    var value = 0
    private val lock = Any()
    private val reentrantLock = ReentrantLock()
    val atomic = AtomicInteger()
    val adder = LongAdder()

    // 重置计数器
    fun reset() {
        value = 0
        atomic.set(0)
        adder.reset()
    }

    // 读取、递增、写入:非原子操作
    fun withoutSynchronization() {
        value++
    }

    // 由 synchronized 保护的临界区
    fun withSynchronized() {
        synchronized(lock) {
            value++
        }
    }

    // synchronized 函数:锁就是 Counter 对象本身
    @Synchronized
    fun withSynchronizedAnnotation() {
        value++
    }

    // 由 ReentrantLock 保护的临界区
    fun withReentrantLock() {
        reentrantLock.withLock {
            value++
        }
    }

    // 原子递增,无锁
    fun withAtomicInteger() {
        atomic.incrementAndGet()
    }

    // 分布式加法器的递增,无锁
    fun withLongAdder() {
        adder.increment()
    }
}

fun main(args: Array<String>) {
    // 参数:线程数、每个线程的递增次数
    val nbThreads = args.getOrNull(0)?.toInt() ?: 4
    val nbIncrements = args.getOrNull(1)?.toInt() ?: 10_000_000
    println("%d threads, %,d increments per thread, expected value %,d"
        .format(nbThreads, nbIncrements, nbThreads * nbIncrements))

    // 递增共享计数器的六种方式
    val value = { Counter.value.toLong() }
    measure("without synchronization", nbThreads, nbIncrements, Counter::withoutSynchronization, value)
    measure("with synchronized", nbThreads, nbIncrements, Counter::withSynchronized, value)
    measure("with @Synchronized", nbThreads, nbIncrements, Counter::withSynchronizedAnnotation, value)
    measure("with ReentrantLock", nbThreads, nbIncrements, Counter::withReentrantLock, value)
    measure("with AtomicInteger", nbThreads, nbIncrements, Counter::withAtomicInteger) {
        Counter.atomic.get().toLong()
    }
    measure("with LongAdder", nbThreads, nbIncrements, Counter::withLongAdder, Counter.adder::sum)
}

// 启动所有执行 [increment] nbIncrements 次的线程,然后显示 [value]
fun measure(method: String, nbThreads: Int, nbIncrements: Int, increment: () -> Unit, value: () -> Long) {
    Counter.reset()
    // 一个启动信号,使所有线程同时开始
    val startSignal = CountDownLatch(1)
    val threads = List(nbThreads) {
        Thread.ofPlatform().start {
            try {
                startSignal.await()
            } catch (_: InterruptedException) {
                return@start
            }
            repeat(nbIncrements) { increment() }
        }
    }
    // 开始!
    val begin = System.nanoTime()
    startSignal.countDown()
    threads.forEach { it.join() }
    val duration = (System.nanoTime() - begin) / 1_000_000
    println("%-23s : value obtained %,12d in %5d ms".format(method, value(), duration))
}

注释:

  • 第 11–59 行:[Counter] 对象把计数器和六个递增函数组合在一起;
  • 第 12–14 行:计数器是[@Volatile]。这阻止了编译器执行我们在[Threads09.kt]中观察到的即时优化:每次递增实际上都会读取和写入内存;
  • 第 29 行:不同步的递增;
  • 第 33–35 行:在由函数[synchronized] 和私有锁保护的临界区内进行递增;
  • 第 40–42 行:函数[withSynchronizedAnnotation] 被标注为[@Synchronized]:它的整个函数体就是一个临界区,其锁就是对象[Counter] 本身;
  • 第 46–48 行:在由[ReentrantLock]保护的临界区内递增,使用函数[withLock];
  • 第 54 行:原子递增;
  • 第 59 行:递增[LongAdder];
  • 第 71–79 行:函数[measure] 使用六个不同的递增函数(作为绑定引用传入([Counter::withoutSynchronization]……))来调用,并附带一个返回结果值的函数,其类型为[() -> Long]。对于前四个,是第 71 行的 lambda [value] 把计数器的[Int] 转换为[Long] (Kotlin 中没有隐式转换);对于[AtomicInteger],它是一个尾随 lambda;对于[LongAdder],引用[Counter.adder::sum] 绑定到某个特定对象的方法[sum] ,它本身就返回[Long]。在 Java 中,必须选择函数式接口[Runnable] 和[LongSupplier];在 Kotlin 中,函数类型[() -> Unit] 和[() -> Long] 就足够了;
  • 第 83–102 行:函数[measure] 启动[nbThreads] 个线程,每个线程调用所接收的函数[nbIncrements] 次,并测量总时间。格式[%,12d] 把值右对齐到 12 个字符,并带有千位分隔符;[%-23s] 把方法名称左对齐到 23 个字符;
  • 第 86、90 和 99 行:线程全都在一个 *[CountDownLatch]* 后面等待,该对象在它们全部启动之后才被打开。这使它们能够同时开始工作,使并发访问比线程一个接一个启动时更有可能发生。如果等待被中断,[return@start] 语句(第 92 行)会终止传给[start]的 lambda:在 lambda 内,单独的[return] 会退出外层函数,而这里不允许这样做;因此我们使用标签来指定要退出的是哪个 lambda(第 7 章)。

结果:

1
2
3
4
5
6
7
8
> gradlew -q run -Pmain=threads17.Threads17Kt
4 threads, 10,000,000 increments per thread, expected value 40,000,000
without synchronization : value obtained   39,809,654 in  1831 ms
with synchronized       : value obtained   40,000,000 in  4482 ms
with @Synchronized      : value obtained   40,000,000 in  4883 ms
with ReentrantLock      : value obtained   40,000,000 in  4360 ms
with AtomicInteger      : value obtained   40,000,000 in  1588 ms
with LongAdder          : value obtained   40,000,000 in  2143 ms
  • 在没有同步的情况下,结果再次不正确:注解[@Volatile] 没有使[value++] 成为原子操作。丢失的更新数量每次执行差别很大;
  • 其他五种方法产生了正确的结果,并且这是可重现的;
  • 在这次运行中,原子类明显比锁快。这里锁的代价很高,因为四个线程在一个微小的操作上不断地竞争它们。函数[synchronized] 和注解[@Synchronized] 的代价相近:它们是同一机制,即 JVM 的监视器的两种实现。测得的执行时间在很大程度上取决于机器及其负载(这台机器只有两个处理器,并且被其他程序大量占用):只有它们的数量级才有意义,而且每次运行时,相近方法之间的排名都会变化。[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.kt] 会造成死锁,并使用[tryLock] 方法(来自[ReentrantLock])实现了最后一种解决方案:

// 死锁:两个线程以不同的顺序获取两个锁
package threads18

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds

fun main() {
    // 两个共享资源的锁
    val lockR1 = ReentrantLock()
    val lockR2 = ReentrantLock()

    // T1 先获取 R1 再请求 R2;2 秒后放弃
    val t1 = thread(name = "T1") { work(lockR1, "R1", lockR2, "R2", 2.seconds) }
    // T2 先获取 R2 再请求 R1;最多等待 5 秒
    val t2 = thread(name = "T2") { work(lockR2, "R2", lockR1, "R1", 5.seconds) }
    t1.join()
    t2.join()
    println("End of Main")
}

// 获取第 1 个资源,然后尝试在 [timeout] 内获取第 2 个
fun work(first: Lock, firstName: String, second: Lock, secondName: String, timeout: Duration) {
    val name = Thread.currentThread().name
    first.withLock {
        println("${time()} : $name obtained $firstName")
        try {
            // 给另一个线程留出获取其第一个资源的时间
            Thread.sleep(500)
            println("${time()} : $name requests $secondName")
            // 带最长等待时间的请求,而不是会无限等待的 lock()
            if (second.tryLock(timeout.inWholeMilliseconds, TimeUnit.MILLISECONDS)) {
                try {
                    println("${time()} : $name obtained $secondName" +
                            " and works with $firstName and $secondName")
                } finally {
                    second.unlock()
                }
            } else {
                println("${time()} : $name did not obtain $secondName in ${timeout.inWholeSeconds} s:" +
                        " it releases $firstName and gives up")
            }
        } catch (_: InterruptedException) {
            Thread.currentThread().interrupt()
        }
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

注释:

  • 第 16–17 行:两个资源的锁。这里它们是局部变量,被第 20 行和第 22 行的 lambda 所捕获;
  • 第 20 行:线程 T1 由函数[thread]创建并启动,它获取 R1,然后请求 R2;它最多等待 2 秒钟。该持续时间写作[2.seconds]:这是 Kotlin 标准库中类型为[kotlin.time.Duration] 的值,由[seconds] 这个[Int]的扩展属性构造(从[Duration.Companion]导入)。这相当于 Java 的[Duration.ofSeconds(2)] ([java.time.Duration]),但可读性更好;
  • 第 22 行:线程 T2 获取 R2,然后请求 R1——也就是按相反的顺序;它最多等待 5 秒钟;
  • 第 29 行:函数[work] 接收由接口[Lock]定义的类型的锁,该接口由[ReentrantLock]实现;
  • 第 31 行:线程使用前面描述的[withLock] 函数获取其第一个资源:无论如何,它都会在块结束时释放它;
  • 第 35 行:它等待半秒钟,这让另一个线程有时间获取它自己的第一个资源:此时死锁就确定无疑了;
  • 第 38 行:线程不使用会无限期等待的 *[lock] ,而是带最长等待时间来请求第二个锁。如果获得了锁,[tryLock] 返回[true] ,如果超时则返回[false] 。超时用一个数字和一个单位来表示([TimeUnit.MILLISECONDS]);属性[inWholeMilliseconds] 以毫秒为单位返回持续时间[timeout] 。这里不能使用调用了[withLock] 的[lock]:你必须自己写出[try { … } finally { second.unlock() }]*;
  • 第 43 行:由[tryLock] 获取的锁必须由[unlock]释放,且在[finally] 子句中;
  • 第 45–47 行:如果未能获取第二个锁,线程就中止。退出[withLock] 块时,它会释放自己的第一个资源;
  • 第 49–50 行:带超时的[sleep] 和[tryLock] 可能抛出[InterruptedException]。Kotlin 不要求捕获这个异常(它没有受检异常),但编写良好的线程会捕获它并重置中断标志,正如我们在中断一节中所见。

结果:

1
2
3
4
5
6
7
8
> gradlew -q run -Pmain=threads18.Threads18Kt
13:00:59.694 : T2 obtained R2
13:00:59.692 : T1 obtained R1
13:01:00.204 : T1 requests R2
13:01:00.205 : T2 requests R1
13:01:02.205 : T1 did not obtain R2 in 2 s: it releases R1 and gives up
13:01:02.224 : T2 obtained R1 and works with R2 and R1
End of Main

两个线程各自获得了第一个资源,然后请求第二个资源:它们陷入了死锁。2 秒钟之后,T1 放弃并释放 R1;仍在等待的 T2 立即获得 R1,并且可以开展工作。如果没有超时,程序永远不会结束。这一事件序列是可重现的;只有第 1 行和第 2 行的顺序以及第 3 行和第 4 行的顺序可能会改变(顺便注意,前两行中的时间并不按顺序:一个线程先读取了时间,但另一个线程先显示了消息)。我们无法使用[synchronized] 函数来编写这个程序,因为它的等待时间无法被限制。

当 Kotlin 程序看起来被阻塞时,JDK 的[jcmd <pid> Thread.print] 命令会显示其每个线程的调用栈([pid] 是进程 ID,不带任何参数的[jcmd] 命令会返回它);它能检测锁之间的死锁,并用消息“Found one Java-level deadlock”报告,随后列出所涉及的线程和锁。IntelliJ 调试器(IDEA)提供同样的功能(Get Thread Dump 按钮)。

8.8.2. 示例:读者与写者

请看下面的示例:

  • 我们有一个数组,一些线程向其中写入数据(写者),另一些线程读取数据(读者);
  • 写者彼此平等但互斥:一次只有一个写者可以向数组中存放数据;
  • 读者彼此平等但互斥:一次只有一个读者可以读取存储在数组中的数据;
  • 只有当写者在数组中放入了数据时,读者才能从数组中读取数据;只有当数组中已有的数据被读者读取之后,写者才能在数组中放入新数据。

共享资源有两种类型:

  • 可写表:一次只有一个写者可以访问它;
  • 只读表:一次只有一个读者可以访问它。

以及使用这些资源的顺序:

  • 读者必须始终跟在写者之后;
  • 写者必须始终跟在读者之后,第一次除外。

对这两个资源的访问可以通过两个[Semaphore] 类型的屏障来控制:

  • [canWrite] 屏障控制写者对数组的访问;
  • [canRead] 屏障控制读者对数组的访问;
  • [canWrite] 屏障被创建为打开状态(一个许可),允许第一个写者通过并阻塞所有其他写者;
  • [canRead] 屏障被创建为关闭状态(没有许可),阻塞所有读者;
  • 当写者完成其工作时,它打开屏障[canRead] ,让一个读者进入;
  • 读线程完成工作后,会打开屏障 [canWrite] ,让一个写线程进入。

这里可以看到不属于任何线程的屏障的优势:屏障 [canRead] 由读线程关闭(获取许可),由写线程打开(归还许可)。这对锁来说是不可能的,因为锁只能由持有它的线程释放。演示这种同步的程序 [Threads19.kt] 如下:

// 由两个信号量同步的读者和写者
package threads19

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.Semaphore
import kotlin.concurrent.thread
import kotlin.random.Random

fun main() {
    // 每种线程的数量
    val nbThreads = 2

    // 创建并启动读者线程
    repeat(nbThreads) { i -> thread(name = "R$i") { Board.read() } }
    // 创建并启动写者线程
    repeat(nbThreads) { i -> thread(name = "W$i") { Board.write() } }
    // main 结束:其他线程继续工作
    println("End of Main...")
}

// 共享资源及其同步
object Board {
    // 读者和写者之间共享的数组
    private val data = IntArray(3)
    // 表示可以读取 data 的内容:初始为关闭(无许可)
    private val canRead = Semaphore(0)
    // 表示可以写入 data:初始为打开(一个许可)
    private val canWrite = Semaphore(1)

    // 读取数组的内容
    fun read() {
        val name = Thread.currentThread().name
        println("Function [read] started by thread $name")
        // 等待读取许可
        canRead.acquireUninterruptibly()
        // 读取数组
        for (number in data) {
            // 等待 0.5 秒:线程让出处理器
            sleep(500)
            println("${time()} : reader $name read the number $number")
        }
        // 允许一个写者
        canWrite.release()
        println("Function [read] finished by thread $name")
    }

    // 写入数组
    fun write() {
        val name = Thread.currentThread().name
        println("Function [write] started by thread $name")
        // 等待写入许可
        canWrite.acquireUninterruptibly()
        // 写入数组
        for (i in data.indices) {
            // 等待 0.5 秒
            sleep(500)
            // 区间 [0, 1000[ 内的随机数
            data[i] = Random.nextInt(0, 1000)
            println("${time()} : writer $name wrote the number ${data[i]}")
        }
        // 允许一个读者
        canRead.release()
        println("Function [write] finished by thread $name")
    }
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

说明:

  • 第 15–17 行:创建并启动两个读线程,然后是两个写线程。函数 [repeat] 会执行其 lambda [nbThreads] 次,并向它传入当前的迭代序号。程序没有保留对这些线程的引用:主线程不会等待它们;
  • 第 19 行:主线程立即结束。进程会一直运行到四个线程(它们不是守护线程)全部结束;
  • 第 23 行:共享资源及其同步机制被组织在一个单例对象中,就像前面程序中的 [Counter] 对象一样(Java 使用带有 [static] 成员的嵌套类);
  • 第 25 行:数组 [data] 是一个包含三个元素的 [IntArray] (编译为 [int[]]),是读线程与写线程之间的共享资源;
  • 第 27 行:屏障 [canRead] 向读线程表明它们可以读取数组。它由填充完数组的写线程打开。它创建时处于关闭状态:必须先由写线程填充数组;
  • 第 29 行:屏障 [canWrite] 通知写线程可以写入数组。它由读完整个数组的读线程打开。它创建时处于打开状态:数组一开始就是可写的;
  • 第 36 行:读线程等待写线程发出数组已填充的信号。该信号到达时,只有一个等待中的读线程继续执行;
  • 第 38–41 行:读取数组,每个元素之间暂停半秒,以迫使线程让出 CPU;
  • 第 44 行:读线程通知写线程,数组已读完,可以再次填充;
  • 函数 [write] 与函数 [read] 是对称的。第 55 行的循环遍历数组的索引(***[data.indices] 即区间 ***[0..2]);
  • 第 59 行:数字由 Kotlin 标准库的 [Random] 对象([kotlin.random.Random])随机生成。函数 [nextInt(0, 1000)] 返回区间 [0, 1000[ 内的一个整数。生成器 [Random] 可以被多个线程使用:在 JVM 上,它依赖 [ThreadLocalRandom] 类(Java 7),该类为每个线程提供各自的生成器,因此线程之间不会争用同一个生成器。Java 代码则直接使用 [ThreadLocalRandom.current().nextInt(0, 1000)];
  • 数组 [data] 没有受到任何锁的保护。然而这里不存在数据竞争:写线程的写入先于它的 [canRead.release()],后者又先于(happens-before 关系)读线程的 [canRead.acquireUninterruptibly()],因此也先于它的读取。

结果:

> gradlew -q run -Pmain=threads19.Threads19Kt
Function [read] started by thread R1
Function [write] started by thread W0
End of Main...
Function [write] started by thread W1
Function [read] started by thread R0
12:46:35.516 : writer W0 wrote the number 760
12:46:36.029 : writer W0 wrote the number 133
12:46:36.530 : writer W0 wrote the number 35
Function [write] finished by thread W0
12:46:37.031 : reader R1 read the number 760
12:46:37.532 : reader R1 read the number 133
12:46:38.032 : reader R1 read the number 35
Function [read] finished by thread R1
12:46:38.533 : writer W1 wrote the number 277
12:46:39.033 : writer W1 wrote the number 724
12:46:39.534 : writer W1 wrote the number 375
Function [write] finished by thread W1
12:46:40.035 : reader R0 read the number 277
12:46:40.536 : reader R0 read the number 724
12:46:41.036 : reader R0 read the number 375
Function [read] finished by thread R0

以下几点值得注意:

  • 同一时刻只有一个读线程,尽管它在临界区 [read] 中会失去 CPU;
  • 同一时刻只有一个写线程,尽管它在临界区 [write] 中会失去处理器;
  • 读线程只有在数组中有内容可读时才会读取;
  • 写线程只有在数组被完整读完后才会写入;
  • 不过,执行顺序是无法控制的:这里读线程 R1 先于读线程 R0 运行,尽管 R0 是先启动的;写线程 W0 也没有理由一定先于写线程 W1 运行。再次执行时,顺序可能不同。

8.8.3. wait 和 notifyAll 方法

在前面的例子中,当写线程在 [canWrite.acquireUninterruptibly()] 语句上阻塞时,其中任意一个线程会被 [canWrite.release()] 操作解除阻塞。如果想为某个特定的写线程打开屏障,事情就会复杂一些。

以设有服务窗口的公共服务大厅为类比。顾客到达时,从取号机领取一张编号的号牌,然后去坐下。顾客通过扬声器按号码被叫到。等待期间,顾客可以随意做自己的事:看书或打盹。每当扬声器报出一个号码,他们就会被唤醒。如果是自己的号码,顾客就起身前往窗口;否则就继续做原来的事。我们可以用类似的方式处理线程。以写线程为例:

在窗口
对线程而言
几位写线程等待同一个窗口
它们的线程被阻塞
窗口空闲,叫到下一位写线程的号码
读取数组的线程通知写线程数组已可用。由该线程或另一个线程确定轮到哪个写线程继续
每位写线程核对自己的号码;只有被叫到号码的那一位前往窗口,其余的回到等待队列
每个线程检查自己是否是被选中的线程。如果是,就通过屏障;否则回到等待队列

JVM 允许使用 任何 Java 对象可用的方法来实现这个场景,因为这些方法定义在 [java.lang.Object] 类中:

方法
作用
[wait()]
归还对象的监视器,并阻塞线程,直到另一个线程通过 [notify] 或 [notifyAll] 发出变化信号;线程随后必须重新取得监视器才能继续。等待可以被中断 ([InterruptedException])
[wait(ms: Long)]
同上,但有最长等待时间
[notify()]
唤醒在此对象上被 [wait] 阻塞的某一个线程
[notifyAll()]
唤醒在此对象上被 [wait] 阻塞的所有线程

在 Kotlin 中,这些方法不能直接访问。Kotlin 的根类是 [Any],而不是 [Object]:编译器会映射这两个类型(*[Any] 会被编译为 *[java.lang.Object]*),但 *[Any] 只声明了三个函数:*[equals]*、[hashCode]、和 [toString]。方法 [wait]、[notify]、和 [notifyAll] (以及 [getClass])被有意省略:Kotlin 的设计者认为这种底层机制不应充斥所有对象,最好使用 [java.util.concurrent] 提供的工具。如果我们用一个 [val token = Any()] 令牌来编写:

synchronized(token) { token.wait() }

编译器会给出如下响应:

error: unresolved reference 'wait' on receiver of type 'Any'.

要调用 [wait],需要一个在编译器看来类型为 [java.lang.Object] 的对象。可以将类型转换为 [(token as Object).wait()],或者直接用 [Object()] 创建令牌。两种情况下,编译器都会发出警告:

warning: this class is not recommended for use in Kotlin. Use 'kotlin.Any' instead.

由于我们的程序是用将警告视为错误的选项编译的([allWarningsAsErrors = true]),必须通过在使用类 [@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")] 的声明上添加注解 [Object] 来显式禁用它([PLATFORM_CLASS_MAPPED_TO_KOTLIN] 是该警告的名称:“与 Kotlin 类关联的平台类”)。我们在下面的令牌声明中一次性完成这件事:它们的类型随后是 [java.lang.Object],调用 [token.wait()] 和 [token.notifyAll()] 不再触发警告。这个小小的不便是有意为之:在 Kotlin 中,我们更倾向于使用下一节介绍的 [Condition] 接口。尽管如此,熟悉 [wait] 和 [notifyAll] 仍然有用,因为在大量现有的 Java 代码中都会遇到它们。

下面我们描述一种标准模式——Brian Goetz 等人的著作 [Java Concurrency in Practice] 中尤其介绍过——它可以解决带有进入条件的屏障问题。

共享资源(计数器)的线程通过一个我们称为 令牌的对象来访问它:它是一个简单对象([Object()]),使用的是它的监视器。要通过通向计数器的屏障,必须持有令牌,而令牌只有一个。因此线程之间必须相互传递令牌。

要前往计数器,线程首先使用 [synchronized(token) { … }] 块请求令牌。如果获得令牌,它就在 [while (!iAmTheExpectedOne) { token.wait() }] 循环中检查自己是否满足前往计数器的条件,然后仍在 [synchronized] 块内前往计数器。如果该线程不是计数器处所期待的线程,它就通过 [token.wait()] 归还令牌,让出自己的轮次,并进入阻塞状态。当另一个线程发出访问条件发生变化的信号时,它会被唤醒;然后它会取回令牌并再次检查条件。这就是为什么此处的测试是循环([while]) 而不是简单的 [if]。还有第二个原因,是 JVM 特有的:规范允许“虚假唤醒”,即 [wait] 在没有任何线程调用 [notify] 的情况下结束;循环使这种情况无害。[token.wait()] 操作只能由持有令牌监视器的线程执行;否则会抛出 [IllegalMonitorStateException] 异常。在这种方案中,令牌只有在事务完成之后才会释放。

修改计数器访问条件的线程同样必须持有令牌,并通知等待中的线程:它在 [synchronized(token) { … }] 块内修改计数器的访问条件,然后使用 [token.notifyAll()] 唤醒等待中的线程。

唤醒线程意味着等待中的线程成为令牌的候选者;它们并不会立即获得令牌。只有在 [synchronized] 块结束时令牌才可用。所有被唤醒的线程随后会 依次以不确定的顺序获得令牌,从而有机会再次检查访问条件。第一个满足条件的线程保留令牌并前往窗口排队。

有了这些信息,我们就可以重写读/写应用程序,指定读线程和写线程前往各自计数器的顺序([Threads20.kt]):

// 读者和写者按规定的顺序访问计数器:wait / notifyAll
package threads20

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread
import kotlin.random.Random

fun main() {
    // 每种线程的数量
    val nbThreads = 3

    // 读者的顺序:与创建顺序相反
    Board.readOrder = List(nbThreads) { i -> "R${nbThreads - 1 - i}" }
    // 写者的顺序:创建顺序
    Board.writeOrder = List(nbThreads) { i -> "W$i" }
    for (i in 0..<nbThreads) {
        println("Reader ${Board.readOrder[i]} is in position $i," +
                " writer ${Board.writeOrder[i]} is in position $i")
    }

    // 先创建并启动读者线程,再创建并启动写者线程
    repeat(nbThreads) { i -> thread(name = "R$i") { Board.read() } }
    repeat(nbThreads) { i -> thread(name = "W$i") { Board.write() } }

    // 写入许可
    Board.allowWriting()
    // main 结束
    println("End of Main...")
}

// 共享资源及其同步
object Board {
    // 读者和写者之间共享的数组
    private val data = IntArray(3)
    // 读计数器和写计数器的访问令牌:
    // java.lang.Object 对象,用于使用 wait 和 notifyAll
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    private val canRead = Object()
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    private val canWrite = Object()
    // 计数器的访问条件
    private var readingAllowed = false
    private var writingAllowed = false
    private var nextReader = 0
    private var nextWriter = 0
    // 读者和写者的顺序
    var readOrder = listOf<String>()
    var writeOrder = listOf<String>()

    // 打开写计数器
    fun allowWriting() {
        synchronized(canWrite) {
            writingAllowed = true
            // 唤醒所有等待该令牌的写者
            canWrite.notifyAll()
        }
    }

    // 读取数组的内容
    fun read() {
        val name = Thread.currentThread().name
        println("Function [read] started by thread $name")
        // 请求读计数器的令牌
        synchronized(canRead) {
            try {
                // 只要还没轮到我们,就归还令牌并等待
                while (!readingAllowed || readOrder[nextReader] != name) {
                    canRead.wait()
                }
            } catch (_: InterruptedException) {
                return
            }
            // 在计数器处:读取数组
            for (number in data) {
                sleep(500)
                println("${time()} : reader $name read the number $number")
            }
            // 下一个读者
            readingAllowed = false
            nextReader++
            // 通知写者可以写入了
            synchronized(canWrite) {
                writingAllowed = true
                canWrite.notifyAll()
            }
            println("Function [read] finished by thread $name")
        }
    }

    // 写入数组
    fun write() {
        val name = Thread.currentThread().name
        println("Function [write] started by thread $name")
        // 请求写计数器的令牌
        synchronized(canWrite) {
            try {
                // 只要还没轮到我们,就归还令牌并等待
                while (!writingAllowed || writeOrder[nextWriter] != name) {
                    canWrite.wait()
                }
            } catch (_: InterruptedException) {
                return
            }
            // 在计数器处:写入数组
            for (i in data.indices) {
                sleep(500)
                data[i] = Random.nextInt(0, 1000)
                println("${time()} : writer $name wrote the number ${data[i]}")
            }
            // 下一个写者
            writingAllowed = false
            nextWriter++
            // 通知读者可以读取了
            synchronized(canRead) {
                readingAllowed = true
                canRead.notifyAll()
            }
            println("Function [write] finished by thread $name")
        }
    }
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

读计数器的访问受以下元素控制:

  • 第 39 行:令牌 [canRead],其前面(第 38 行)有一个用于禁用类 [Object] 警告的注解;
  • 第 43 行:布尔值 [readingAllowed];
  • 第 48 行:读线程名称的有序列表。读线程按此列表的顺序前往读取窗口;
  • 第 45 行:[nextReader] 是该列表中下一个获准前往窗口的读线程的索引。

写计数器的访问同样由令牌 [canWrite]、布尔值 [writingAllowed]、列表 [writeOrder]、以及索引 [nextWriter] 控制。

主程序:

  • 第 14–16 行:读线程按创建顺序的相反顺序前往计数器(R2、R1、R0),写线程按创建顺序前往(W0、W1、W2)。列表由函数 [List] 构造,它为每个索引调用其 lambda。Java 代码使用的是流([IntStream.range(0, nbThreads).mapToObj(…).toList()]);
  • 第 17 行:区间 [0..<nbThreads] 不包含其上界:它等价于 [0 until nbThreads];
  • 第 23–24 行:创建并启动读线程,然后是写线程。由于读和写都未获允许,它们都会被阻塞;
  • 第 27 行:允许写入,并通知写线程有变化发生(函数 [allowWriting],第 52–56 行)。

函数 [read]:

  • 第 65–87 行:读取窗口处的整个过程由 [synchronized] 块针对令牌 [canRead] 控制。获得令牌的读线程在整个窗口办理期间一直持有它;
  • 第 68–69 行:已获得令牌的读线程,如果不允许读取或者还没轮到它,就归还令牌。名称通过运算符 [!=] 比较,它比较的是内容(调用 [equals]);
  • 第 71–72 行:如果线程在等待期间被中断,它就中止。这里的 [return] 写在传给 [synchronized] 的 lambda 中;这是允许的,因为 [synchronized] 是一个 [inline] 函数 (第 7 章):这个 [return] 会终止函数 [read],同时监视器也被释放;
  • 第 75–77 行:前往窗口(读取表);
  • 第 80–81 行:读线程更改读取端口的访问条件。它仍持有读令牌,这些更改会阻止其他任何读线程访问该端口;
  • 第 83–85 行:读线程更改写端口的访问条件,并通知所有等待中的写线程有变化发生。为此它获取令牌 [canWrite]:这里可以看到该线程同时持有两个令牌。写线程则以相反的顺序做同样的事(它们持有 [canWrite] 并请求 [canRead]),这就是前面描述的死锁情形。不过这里没有风险:线程只在访问完计数器之后才请求第二个令牌;两个计数器永远不会同时被占用;其他线程持有令牌的时间只够检查访问条件,并不请求另一个令牌。

函数 [write] 与函数 [read] 对称。请注意这里使用的是 [notifyAll] 而不是 [notify],后者只唤醒单个线程:如果该线程不是预期的写线程,它会重新休眠,而预期的写线程可能永远不会被唤醒。当访问条件指定了某个特定线程时,必须使用 [notifyAll]。

执行示例如下:

> gradlew -q run -Pmain=threads20.Threads20Kt
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
Function [read] started by thread R1
Function [read] started by thread R0
Function [read] started by thread R2
End of Main...
Function [write] started by thread W2
Function [write] started by thread W0
Function [write] started by thread W1
12:48:13.264 : writer W0 wrote the number 320
12:48:13.798 : writer W0 wrote the number 344
12:48:14.311 : writer W0 wrote the number 403
Function [write] finished by thread W0
12:48:14.812 : reader R2 read the number 320
12:48:15.312 : reader R2 read the number 344
12:48:15.813 : reader R2 read the number 403
Function [read] finished by thread R2
12:48:16.327 : writer W1 wrote the number 301
12:48:16.827 : writer W1 wrote the number 270
12:48:17.328 : writer W1 wrote the number 102
Function [write] finished by thread W1
12:48:17.835 : reader R1 read the number 301
12:48:18.335 : reader R1 read the number 270
12:48:18.839 : reader R1 read the number 102
Function [read] finished by thread R1
12:48:19.343 : writer W2 wrote the number 402
12:48:19.844 : writer W2 wrote the number 589
12:48:20.344 : writer W2 wrote the number 985
Function [write] finished by thread W2
12:48:20.859 : reader R0 read the number 402
12:48:21.360 : reader R0 read the number 589
12:48:21.861 : reader R0 read the number 985
Function [read] finished by thread R0

写线程和读线程按指定的顺序依次到各自的窗口办理:W0、R2、W1、R1、W2、R0。与前一个程序不同,这个处理顺序是可重现的;每次执行之间只有“started”消息的顺序会有变化。

8.8.4. 条件:Condition 接口

方法 [wait] 和 [notifyAll] 与对象的监视器相关联,因此与 [synchronized] 块相关联。对于锁 [ReentrantLock],对应的是接口 [java.util.concurrent.locks.Condition]:[Condition] 对象由锁的 [newCondition()] 方法创建,并提供方法 [await()] (相当于 [wait])、[await(time: Long, unit: TimeUnit)]、[signal()] (相当于 [notify])以及 [signalAll()] (相当于 [notifyAll])。它们的用法遵循相同的规则:线程必须持有锁,并且访问条件要在 [while] 循环中测试。这些都是 Java 接口的标准方法:Kotlin 调用它们时无需类型转换,也没有警告。这是 Kotlin 中的首选方案。

关键优势在于,一个锁可以拥有 多个条件,也就是多个不同的队列。在我们的问题中,一个锁就可以保护两个计数器,读线程一个条件,写线程一个条件:读线程结束后只唤醒写线程,而且只唤醒它们。不再有两个令牌,因此也不再需要留意锁的嵌套。程序 [Threads21.kt] 的主程序与 [Threads20.kt] 相同;它的对象 [Board] 如下:

// 共享资源及其同步
object Board {
    // 读者和写者之间共享的数组
    private val data = IntArray(3)
    // 两个计数器共用一把锁
    private val lock = ReentrantLock()
    // 与该锁关联的两个条件:两个不同的等待队列
    private val canRead = lock.newCondition()
    private val canWrite = lock.newCondition()
    // 计数器的访问条件
    private var readingAllowed = false
    private var writingAllowed = false
    private var nextReader = 0
    private var nextWriter = 0
    // 读者和写者的顺序
    var readOrder = listOf<String>()
    var writeOrder = listOf<String>()

    // 打开写计数器
    fun allowWriting() {
        lock.withLock {
            writingAllowed = true
            // 唤醒所有写者,并且只唤醒它们
            canWrite.signalAll()
        }
    }

    // 读取数组的内容
    fun read() {
        val name = Thread.currentThread().name
        println("Function [read] started by thread $name")
        lock.withLock {
            try {
                // 只要还没轮到我们,就归还锁并等待信号
                while (!readingAllowed || readOrder[nextReader] != name) {
                    canRead.await()
                }
            } catch (_: InterruptedException) {
                Thread.currentThread().interrupt()
                return
            }
            // 在计数器处:读取数组
            for (number in data) {
                sleep(500)
                println("${time()} : reader $name read the number $number")
            }
            // 下一个读者
            readingAllowed = false
            nextReader++
            // 通知写者可以写入了
            writingAllowed = true
            canWrite.signalAll()
            println("Function [read] finished by thread $name")
        }
    }

    // 写入数组
    fun write() {
        val name = Thread.currentThread().name
        println("Function [write] started by thread $name")
        lock.withLock {
            try {
                // 只要还没轮到我们,就归还锁并等待信号
                while (!writingAllowed || writeOrder[nextWriter] != name) {
                    canWrite.await()
                }
            } catch (_: InterruptedException) {
                Thread.currentThread().interrupt()
                return
            }
            // 在计数器处:写入数组
            for (i in data.indices) {
                sleep(500)
                data[i] = Random.nextInt(0, 1000)
                println("${time()} : writer $name wrote the number ${data[i]}")
            }
            // 下一个写者
            writingAllowed = false
            nextWriter++
            // 通知读者可以读取了
            readingAllowed = true
            canRead.signalAll()
            println("Function [write] finished by thread $name")
        }
    }
}

说明:

  • 第 6 行:一个单独的非公平锁;
  • 第 8–9 行:由该锁创建的两个条件。它们的类型 [Condition] 是推断出来的;
  • 第 20–24 行:要打开写入窗口,使用函数 [withLock] 获取锁,修改访问条件,然后通过 [canWrite.signalAll()] 唤醒写线程;
  • 第 32–53 行:切换到读取窗口是在持有锁的情况下进行的。函数 [withLock] 取代了 Java 的模式 [lock] / [try] / [finally] / [unlock];
  • 第 35–36 行:在轮到自己之前,读线程在条件 [canRead] 上等待。方法 [await] 在等待期间释放锁,并在返回控制权之前重新获取它;
  • 第 38–40 行:如果线程在等待期间被中断,它会重置自己的中断标志并终止。由于 [withLock] 是一个 [inline] 函数,[return] 会终止函数 [read],而 [withLock] 内部的 [finally] 子句会同时释放锁;
  • 第 51–52 行:读线程授予写入权限并唤醒写线程。它已经持有锁,因此不需要获取第二个令牌。

结果:

> gradlew -q run -Pmain=threads21.Threads21Kt
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
Function [read] started by thread R1
Function [read] started by thread R0
Function [write] started by thread W0
End of Main...
Function [write] started by thread W2
Function [read] started by thread R2
Function [write] started by thread W1
12:49:39.079 : writer W0 wrote the number 955
12:49:39.671 : writer W0 wrote the number 213
12:49:40.173 : writer W0 wrote the number 22
Function [write] finished by thread W0
12:49:40.674 : reader R2 read the number 955
12:49:41.177 : reader R2 read the number 213
12:49:41.677 : reader R2 read the number 22
Function [read] finished by thread R2
12:49:42.179 : writer W1 wrote the number 31
12:49:42.680 : writer W1 wrote the number 113
12:49:43.180 : writer W1 wrote the number 999
Function [write] finished by thread W1
12:49:43.683 : reader R1 read the number 31
12:49:44.183 : reader R1 read the number 113
12:49:44.684 : reader R1 read the number 999
Function [read] finished by thread R1
12:49:45.187 : writer W2 wrote the number 528
12:49:45.687 : writer W2 wrote the number 477
12:49:46.188 : writer W2 wrote the number 473
Function [write] finished by thread W2
12:49:46.689 : reader R0 read the number 528
12:49:47.190 : reader R0 read the number 477
12:49:47.690 : reader R0 read the number 473
Function [read] finished by thread R0

其行为与前一个程序相同:W0、R2、W1、R1、W2、R0。

8.8.5. 多个读线程同时读取:ReadWriteLock

在前面的例子中,读线程是互斥的。在许多应用中,这种限制没有必要:当没有人修改数据时,多个线程可以同时读取。只有写入必须是互斥的:当某个写线程正在修改数据时,任何读线程或其他写线程都不应能访问它。这就是经典的 读写问题,由 [java.util.concurrent.locks.ReadWriteLock] 接口解决。[ReadWriteLock] 对象提供两个相互关联的锁:

  • [readLock()]:读锁,只要没有线程持有写锁,就可以被多个线程同时持有;
  • [writeLock()]:写锁,是互斥的。

Kotlin 标准库在 [kotlin.concurrent] 包中为实现了该接口的 [ReentrantReadWriteLock] 类增加了两个与 [withLock] 类似的扩展函数:[read { … }] 在持有读锁的情况下执行代码块,而 [write { … }] 在持有写锁的情况下执行代码块 ;二者都在代码块结束时释放锁,并返回代码块的值。程序 [Threads22.kt] 如下:

// 多个同时读取的读者,单个写者:ReentrantReadWriteLock
package threads22

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.thread
import kotlin.concurrent.write

fun main() {
    val catalog = Catalog()
    // 三个读者各自两次查询键盘的价格
    val readers = List(3) { i ->
        thread(name = "R$i") {
            catalog.readPrice("keyboard")
            catalog.readPrice("keyboard")
        }
    }
    // 一个晚 0.5 秒启动的写者修改这个价格
    Thread.sleep(500)
    val writer = thread(name = "W") { catalog.changePrice("keyboard", 25) }
    // 等待所有线程结束
    (readers + writer).forEach { it.join() }
}

// 共享资源:价格目录
class Catalog {
    private val prices = mutableMapOf("keyboard" to 20, "mouse" to 10)
    // 读者一把锁,写者一把锁
    private val lock = ReentrantReadWriteLock()

    // 多个线程可以同时持有读锁
    fun readPrice(article: String): Int = lock.read {
        val name = Thread.currentThread().name
        println("${time()} : $name starts reading the price of $article")
        // 长时间读取
        sleep(1000)
        val p = prices.getValue(article)
        println("${time()} : $name read the price of $article: $p")
        p
    }

    // 写锁是独占的:没有读者,也没有其他写者
    fun changePrice(article: String, newPrice: Int) {
        val name = Thread.currentThread().name
        println("${time()} : $name requests the write lock")
        lock.write {
            println("${time()} : $name starts changing the price of $article")
            // 长时间写入
            sleep(1000)
            prices[article] = newPrice
            println("${time()} : $name set the price of $article to $newPrice")
        }
    }
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

说明:

  • 第 28–52 行:共享资源是一个价格目录,存放在由 [mutableMapOf] 创建的可修改字典中(第 29 行),它是一个 [LinkedHashMap];
  • 第 31 行:类 [ReentrantReadWriteLock];
  • 第 34–40 行:函数 [readPrice] 为持续一秒的读取操作获取读锁。它的函数体是一个表达式:[lock.read { … }] 返回的值,即代码块中最后一个表达式的值 [p]。函数 [getValue] 返回与键关联的值,如果键不存在则抛出 [NoSuchElementException] 异常(运算符 [prices[article]] 则会返回 [Int?]);
  • 第 45–53 行:函数 [changePrice] 为持续一秒的修改获取写锁。Kotlin 函数 [write] 有一个特别之处:如果线程已经持有读锁,它会先释放读锁(否则它会与自己死锁:[ReentrantReadWriteLock] 不允许从读锁切换到写锁),然后在代码块结束时重新获取读锁;
  • 第 14–17 行:三个读线程连续两次读取键盘的价格;
  • 第 21–22 行:一个在半秒后启动的写线程修改这个价格;
  • 第 24 行:[+] 运算符构造一个由读线程和写线程组成的新列表,并等待它们结束。

结果:

> gradlew -q run -Pmain=threads22.Threads22Kt
12:50:24.630 : R0 starts reading the price of keyboard
12:50:24.635 : R1 starts reading the price of keyboard
12:50:24.631 : R2 starts reading the price of keyboard
12:50:25.070 : W requests the write lock
12:50:25.643 : R2 read the price of keyboard: 20
12:50:25.651 : R1 read the price of keyboard: 20
12:50:25.651 : R0 read the price of keyboard: 20
12:50:25.652 : W starts changing the price of keyboard
12:50:26.652 : W set the price of keyboard to 25
12:50:26.653 : R1 starts reading the price of keyboard
12:50:26.653 : R0 starts reading the price of keyboard
12:50:26.653 : R2 starts reading the price of keyboard
12:50:27.653 : R0 read the price of keyboard: 25
12:50:27.654 : R2 read the price of keyboard: 25
12:50:27.654 : R1 read the price of keyboard: 25
  • 三个读线程同时读取(第 1–3 行和第 5–7 行):使用标准锁的话,第一批读取需要三秒而不是一秒;
  • 写线程在读取进行期间到达,一直等到读取结束。然后它独自修改了价格;
  • 第二批读线程在写线程到达之后才开始,它们等待修改完成,然后读取新的价格。因此锁 [ReentrantReadWriteLock] 可以防止源源不断的读线程无限期地阻止写线程写入:在写线程等待期间到达的读线程排在写线程之后。这个顺序是可重现的;只有每一批内部读线程的顺序会变化。

只有在读取次数很多且足够耗时的情况下,读写锁才有用。对于非常短的读取,[StampedLock] 类(Java 8)提供“乐观”读取——不加锁——并在事后进行验证。而对于读取非常频繁、修改很少的集合,下一段介绍的并发集合通常是最佳方案。

8.9. 并发集合

前面的例子保护的是非常简单的共享数据(一个计数器、一个数组、一个小字典)。当线程共享一个集合(列表、字典、队列)时,可以用锁保护每一次访问。但是普通的可变集合——无论是 Kotlin 中的([mutableListOf]、[mutableMapOf]、[ArrayDeque])还是 Java 中的([ArrayList]、[HashMap])——并不是为被多个线程同时修改而设计的:不加保护地使用可能导致元素丢失,触发意外的异常([ConcurrentModificationException]),甚至破坏集合的内部结构。Kotlin 的“只读”集合([List]、[Map])也是如此:这种类型只是阻止接收它的代码修改集合,并不保证其他人不会修改它。方法 [Collections.synchronizedList(…)]、[Collections.synchronizedMap(…)]… 把普通集合包装成一个每个方法都是 [synchronized] 类型的对象:这样做是安全的,但所有线程都争用同一把锁,而且对集合的迭代仍需手动保护。自 Java 5 起,[java.util.concurrent] 包就提供了无需显式加锁即可在线程之间共享的集合。Kotlin 标准库在 JVM 上没有对应的实现:我们直接使用 JDK 中的集合,它们实现了 [MutableList] 和 [MutableMap] 接口……因此可以像 Kotlin 集合一样使用([+=]、[[ ]]、[for]、[filter]、[map]…):

集合
作用
[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.kt] 中,四个线程生成随机数,并在一个共享字典中统计每个数字出现的次数:

// 并发集合:ConcurrentHashMap 和 CopyOnWriteArrayList
package threads23

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.concurrent.thread
import kotlin.random.Random

fun main() {
    // 共享字典:数字 -> 抽取次数
    val draws = ConcurrentHashMap<Int, Int>()
    // 各线程报告的共享列表
    val reports = CopyOnWriteArrayList<String>()

    // 4 个线程各自随机抽取 100,000 个数字
    val nbDraws = 100_000
    val threads = List(4) { i ->
        thread(name = "T$i") {
            repeat(nbDraws) {
                val digit = Random.nextInt(0, 10)
                // 添加值为 1 的键,或原子地更新已有的值
                draws.merge(digit, 1, Int::plus)
            }
            // 报告已添加到列表
            val name = Thread.currentThread().name
            reports += "thread %s finished its %,d draws".format(name, nbDraws)
        }
    }
    threads.forEach { it.join() }

    // 报告,按到达顺序排列
    for (report in reports) {
        println(report)
    }
    // 抽取结果,按键的顺序排列
    for ((digit, count) in draws.toSortedMap()) {
        println("digit %d : %,6d draws".format(digit, count))
    }
    val total = draws.values.sum()
    println("total: %,d draws (expected: %,d)".format(total, threads.size * nbDraws))
    // computeIfAbsent:返回与键关联的值,必要时先计算并添加
    println("computeIfAbsent(10, …) = ${draws.computeIfAbsent(10) { 0 }}, number of keys: ${draws.size}")
}

说明:

  • 第 11 行:共享字典将每个数字与其出现次数关联起来。由于字典创建时是空的,因此显式指定了类型 [<Int, Int>] ;
  • 第 13 行:一个列表,每个线程在工作结束时向其中写入一份报告;
  • 第 22 行:方法 [merge(key, value, function)] 在键 [digit] 不存在时以值 1 添加它;否则,将其值 v 替换为 [function(v, 1)],这里是加法,用对 [Int::plus] 的引用来表示,即对 [plus] 函数的引用,该函数属于 [Int] (运算符 [+])。在 [ConcurrentHashMap] 中,该操作是原子的。我们不能写成 [draws[digit] = (draws[digit] ?: 0) + 1]:这个表达式先读取值,再写入新值,分两步操作,两个线程可能会丢失一次更新,就像示例 [Threads09.kt] 中那样;
  • 第 26 行:每个线程使用运算符 [+=] (Kotlin 可变集合的 [plusAssign] 函数,它调用 [add])把自己的报告添加到列表中。[format] 函数来自 [String] ,用于格式化消息;格式 [%,d] 会插入千位分隔符;
  • 第 32–33 行:主线程遍历该列表。对 *[CopyOnWriteArrayList] 的遍历是在内部数组的快照上进行的:即使其他线程在遍历期间修改了列表,它也绝不会抛出 *[ConcurrentModificationException];
  • 第 36–37 行:扩展函数 [toSortedMap] 将字典复制为一个有序字典([TreeMap]),以便按顺序显示数字;[for] 循环把每个条目拆分为键和值;
  • 第 39 行:值的总和,由标准库的 [sum] 函数计算(Java 使用的是流);
  • 第 42 行:方法 [computeIfAbsent(key, function)] 返回与键关联的值;如果键不存在,则先用该函数计算出值并添加,再返回。这里的函数是位于括号之外的尾随 lambda。与 [merge] 一样,检查和添加构成一个单一的原子操作:先做 [containsKey] 检查再做 [put] 是不安全的,因为另一个线程可能在两者之间添加这个键。Kotlin 的 [getOrPut] 扩展函数(我们在普通字典中用过)有一个适用于并发字典([ConcurrentMap])的版本:它不会为已存在的键添加第二个值,但如果两个线程同时添加同一个键,它的 lambda 可能被不必要地调用。[computeIfAbsent] 没有这个缺点。

结果:

> gradlew -q run -Pmain=threads23.Threads23Kt
thread T1 finished its 100,000 draws
thread T3 finished its 100,000 draws
thread T2 finished its 100,000 draws
thread T0 finished its 100,000 draws
digit 0 : 39,946 draws
digit 1 : 40,200 draws
digit 2 : 39,923 draws
digit 3 : 39,656 draws
digit 4 : 39,825 draws
digit 5 : 40,016 draws
digit 6 : 40,081 draws
digit 7 : 39,907 draws
digit 8 : 40,259 draws
digit 9 : 40,187 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] (在 Kotlin 中,[poll] 返回平台类型 [Int!],应将其视为 [Int?])。

队列并不知道生产已经结束。一种经典技术是在生产结束时往队列中放入一个特殊值——英语中称为“poison pill”(毒丸)——取到它的消费者就知道必须停止。另一种技术是中断消费者,因为 [take] 是可中断的。程序 [Threads24.kt] 如下:

// 使用 BlockingQueue 的生产者 / 消费者
package threads24

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import kotlin.concurrent.thread

// 表示生产结束的值("毒丸")
const val END = -1

fun main() {
    // 一个最多容纳 3 个元素的队列
    val queue: BlockingQueue<Int> = ArrayBlockingQueue(3)
    val nbConsumers = 2

    // 生产者放入 8 个数字,然后发出已完成的信号
    val producer = thread(start = false, name = "P") {
        try {
            for (i in 1..8) {
                // 如果队列已满则阻塞
                queue.put(i)
                println("${time()} : P put $i (waiting elements: ${queue.size})")
                Thread.sleep(100)
            }
            // 每个消费者一个结束标记
            repeat(nbConsumers) { queue.put(END) }
            println("${time()} : P has finished")
        } catch (_: InterruptedException) {
            Thread.currentThread().interrupt()
        }
    }

    // 两个消费者取数字,直到遇到结束标记
    val consumers = List(nbConsumers) { i ->
        thread(start = false, name = "C${i + 1}") {
            val name = Thread.currentThread().name
            try {
                while (true) {
                    // 如果队列为空则阻塞
                    val number = queue.take()
                    if (number == END) break
                    println("${time()} : $name took $number")
                    // 处理该数字
                    Thread.sleep(600)
                }
                println("${time()} : $name has finished")
            } catch (_: InterruptedException) {
                Thread.currentThread().interrupt()
            }
        }
    }

    // 启动并等待所有线程
    val all = listOf(producer) + consumers
    all.forEach { it.start() }
    all.forEach { it.join() }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

说明:

  • 第 11 行:标记生产结束的值。这是一个顶层常量,声明在任何类之外([const val],第 3 章);
  • 第 15 行:一个最多容纳 3 个元素的队列。[ArrayBlockingQueue] 将元素存放在固定大小的数组中;[LinkedBlockingQueue] 默认容量不受限制。变量声明为接口类型 [BlockingQueue<Int>],这使编译器能够从构造函数 [ArrayBlockingQueue(3)] 推断出元素的类型;
  • 第 19–29 行:生产者把数字 1 到 8 放入队列,每十分之一秒放一个,然后为每个消费者各放一个结束标记(第 28 行)。函数 [start = false] 的参数 [thread] 会创建线程但不启动它:它将稍后与消费者一起启动;
  • 第 36–48 行:两个消费者取出数字,并花 0.6 秒处理每一个。它们的消费速度比生产者的生产速度慢;
  • 第 42 行:阻塞式移除。每个数字只会被两个消费者中的一个取走;
  • 第 43 行:取到结束标记的消费者退出循环。每个消费者取走一个标记,因此每个消费者放入一个标记;
  • 生产者和消费者都包含 [try] 指令,因为 [put]、[take]、和 [sleep] 可能抛出 [InterruptedException]。Kotlin 并不要求这样做,但如果没有它,该异常会终止线程,并在控制台上显示调用栈;
  • 第 56–58 行:启动所有线程,然后等待它们结束。

结果:

> gradlew -q run -Pmain=threads24.Threads24Kt
12:52:50.226 : P put 1 (waiting elements: 0)
12:52:50.210 : C1 took 1
12:52:50.371 : P put 2 (waiting elements: 1)
12:52:50.374 : C2 took 2
12:52:50.503 : P put 3 (waiting elements: 1)
12:52:50.617 : P put 4 (waiting elements: 2)
12:52:50.737 : P put 5 (waiting elements: 3)
12:52:50.911 : C1 took 3
12:52:50.911 : P put 6 (waiting elements: 3)
12:52:50.974 : C2 took 4
12:52:51.015 : P put 7 (waiting elements: 3)
12:52:51.515 : C1 took 5
12:52:51.517 : P put 8 (waiting elements: 3)
12:52:51.574 : C2 took 6
12:52:52.116 : C1 took 7
12:52:52.118 : P has finished
12:52:52.175 : C2 took 8
12:52:52.716 : C1 has finished
12:52:52.779 : C2 has finished

我们看到生产者很快添加了最初的几个数字,然后——一旦队列中有 3 个元素——只有在消费者取走一个时才添加一个数字:队列已满时它被 [put] 阻塞。消费者彼此分担这些数字,并在取到结束标记时停止。这个节奏是可重现的;但每个数字分配给 C1 还是 C2 则不是。生产者只有在放入两个结束标记之后才显示“P has finished”,也就是在 C1 取走数字 7 并腾出一个空位之后。我们还注意到,在前两行中,数字 1 在 P 显示其放入操作之前就已被 C1 取走(因此显示“waiting elements: 0”),尽管 C1 读取的时间早于 P 读取的时间:每个线程先读取时间再打印,而另一个线程可能在这两步之间插入执行。

我们将在下一章再次看到这种模式,那时会用到协程通道([Channel]),它是阻塞队列在协程中的对应物:它们的操作 [send] 和 [receive] 挂起的是协程,而不是阻塞线程。使用虚拟线程时,在 [take] 上阻塞的消费者不会占用任何系统线程。

8.10. 线程池:ExecutorService

8.10.1. 原理

到目前为止,为了管理线程,我们都是先创建线程再启动它,或者通过 [start()] ,或者通过 [thread] 函数。创建平台线程是一项相对昂贵的操作:尤其是系统必须为它分配栈,而且每个线程在存在期间都会占用内存。我们将在第 10 章看到连接池的存在:已打开的连接被保留备用,并借给请求它们的线程,因为打开连接的开销很大。线程也有类似的机制:线程池。

JDK 类通过 [java.util.concurrent.ExecutorService] 接口(“执行器”)来表示线程池:不再创建线程,而是把 任务分配给执行器,由它的线程来执行。完成了任务的线程不会被销毁,而是接着处理下一个任务。[ThreadPoolExecutor] 类是最常见的实现,其工作方式如下:

  • 它有 固定数量的线程(“核心线程池大小”):只要未达到这个数量,每个新任务都会触发创建一个新线程;
  • 超过这个数量后,任务被放入一个 队列 (一个 [BlockingQueue]),线程从中取出任务;
  • 如果队列已满,线程池会创建额外的线程,直到达到 最大数量(“最大线程池大小”)。这些额外的线程如果空闲超过一定时间就会被销毁;
  • 如果已达到最大数量且队列已满,任务就会被 拒绝:默认情况下,提交该任务的方法会抛出 [RejectedExecutionException] 异常。

线程池有两个优点:它节省了创建线程所花的时间(少量线程就能处理数百个请求),并且通过限制线程数量,防止应用程序被过多的请求压垮。

执行器通过其方法 [shutdown] 终止(它不再接受新任务,已提交的任务完成后其线程停止),之后还可以接着调用 [awaitTermination] (等待任务完成),或者调用 [shutdownNow] (中断正在执行的任务)。从 Java 19 起,[ExecutorService] 扩展了 [AutoCloseable] 接口:它的 [close] 方法调用 [shutdown] ,然后等待所有任务完成。因此在 Kotlin 中,可以在 [use { … }] 块内使用执行器——这是 [AutoCloseable] 的扩展函数,用来取代 Java 的带资源的 [try] 语句(第 3 章)——退出该块时,所有已分配的任务都已完成。程序 [Threads25.kt] 如下:

// 线程池:ThreadPoolExecutor
package threads25

import java.time.Duration
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

// 传递给每个作业的信息
data class Data(val number: Int, val start: LocalTime, val duration: Int)

fun main() {
    Thread.currentThread().name = "Main"
    // 3 个常驻线程,最多 5 个线程,一个容纳 2 个作业的等待队列
    ThreadPoolExecutor(3, 5, 60, TimeUnit.SECONDS, ArrayBlockingQueue(2)).use { pool ->
        // 8 个各 3 秒的作业交给线程池
        for (i in 0..<8) {
            val data = Data(i, LocalTime.now(), 3)
            try {
                pool.execute { sleep(data, pool) }
            } catch (_: RejectedExecutionException) {
                println("${time()} : job no. $i was rejected by the pool")
            }
        }
        println("${time()} : thread Main handed the jobs to the pool and waits for their end")
        // use 块结束时关闭线程池:close() 等待已提交的作业结束
    }
    println("${time()} : end of thread Main")
}

// 由线程池中的线程执行的作业
fun sleep(data: Data, pool: ThreadPoolExecutor) {
    // 线程池的状态
    val name = Thread.currentThread().name
    println("${time()} : job no. ${data.number} starts in thread $name" +
            " (threads: ${pool.poolSize}, active: ${pool.activeCount}, queued: ${pool.queue.size})")
    // 休眠 [duration] 秒
    try {
        Thread.sleep(data.duration * 1000L)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
    val duration = Duration.between(data.start, LocalTime.now()).toMillis() / 1000.0
    println("%s : job no. %d ends: scheduled for %d s, it lasted %.2f s since it was requested"
            .format(time(), data.number, data.duration, duration))
}

// 当前时间,精确到百分之一秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SS"))

说明:

  • 第 18 行:线程池有 3 个常驻线程,最多 5 个线程;任何空闲了 60 秒的额外线程都会被销毁;任务队列是一个有 2 个位置的 [ArrayBlockingQueue] (其元素类型 [Runnable] 是从构造函数参数推断出来的)。线程池在 [use] 块中使用,该块将其命名为 [pool];
  • 第 20–25 行:8 个作业,每个持续 3 秒,被分配给线程池。方法 [execute(Runnable)] 将任务分配给线程池而不等待;lambda [{ sleep(data, pool) }] 被转换为 [Runnable] (SAM 转换,第 7 章);
  • 第 21 行:每个作业接收一个 [Data] 对象;这是一个数据类(第 13 行),其作用与 Java 的 [record] 相同;
  • 第 24–25 行:被线程池拒绝的作业会触发 [RejectedExecutionException] 异常;
  • 第 29 行:退出 [use] 块会关闭线程池,并等待已分配的作业完成;
  • 第 35–48 行:由线程池中的线程执行的作业。线程名称([pool-1-thread-1]…)由线程池分配;
  • 第 39 行:线程池的状态:线程数、当前正在执行任务的线程数,以及队列中等待的任务数。Java 方法 [getPoolSize]、[getActiveCount]和 [getQueue] 在 Kotlin 中被当作属性:[poolSize]、[activeCount]、[queue];
  • 第 52 行:时间显示到百分之一秒([SS])。

结果:

> gradlew -q run -Pmain=threads25.Threads25Kt
13:01:02.48 : job no. 1 starts in thread pool-1-thread-2 (threads: 3, active: 3, queued: 0)
13:01:02.48 : job no. 2 starts in thread pool-1-thread-3 (threads: 4, active: 4, queued: 2)
13:01:02.48 : job no. 5 starts in thread pool-1-thread-4 (threads: 5, active: 5, queued: 2)
13:01:02.48 : job no. 0 starts in thread pool-1-thread-1 (threads: 2, active: 2, queued: 0)
13:01:02.48 : job no. 7 was rejected by the pool
13:01:02.50 : thread Main handed the jobs to the pool and waits for their end
13:01:02.48 : job no. 6 starts in thread pool-1-thread-5 (threads: 5, active: 5, queued: 2)
13:01:05.49 : job no. 5 ends: scheduled for 3 s, it lasted 3.01 s since it was requested
13:01:05.51 : job no. 3 starts in thread pool-1-thread-4 (threads: 5, active: 5, queued: 1)
13:01:05.50 : job no. 6 ends: scheduled for 3 s, it lasted 3.03 s since it was requested
13:01:05.51 : job no. 4 starts in thread pool-1-thread-5 (threads: 5, active: 5, queued: 0)
13:01:05.49 : job no. 1 ends: scheduled for 3 s, it lasted 3.02 s since it was requested
13:01:05.50 : job no. 0 ends: scheduled for 3 s, it lasted 3.03 s since it was requested
13:01:05.49 : job no. 2 ends: scheduled for 3 s, it lasted 3.01 s since it was requested
13:01:08.51 : job no. 3 ends: scheduled for 3 s, it lasted 6.03 s since it was requested
13:01:08.51 : job no. 4 ends: scheduled for 3 s, it lasted 6.03 s since it was requested
13:01:08.51 : 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 必须等到前面的作业结束后有线程空闲:这里它们重用了线程 4 和 5——最先空闲出来的两个额外线程。从提出请求起,它们总共花了略多于 6 秒:3 秒等待和 3 秒处理;
  • 每个作业启动时显示的值(线程数、队列)取决于它获得处理器的确切时刻:它们每次执行都不同,作业 3 和 4 重用的线程也是如此。不过,每个作业的结果(立即执行、在队列中等待或被拒绝)是可重现的。

你很少需要自己构建 *[ThreadPoolExecutor] :*[Executors] 类为常见情形提供了构造方法:

方法
返回的执行器
[newFixedThreadPool(n)]
一个有 n 个常驻线程的线程池,任务队列容量不受限制
[newCachedThreadPool()]
一个没有常驻线程的线程池,它按需创建任意数量的线程,并销毁空闲 60 秒的线程
[newSingleThreadExecutor()]
单个线程,按提交的顺序逐个执行任务
[newScheduledThreadPool(n)]
一个能够延迟执行或周期性执行任务的线程池(接口 [ScheduledExecutorService])
[newVirtualThreadPerTaskExecutor()]
(Java 21)一个没有线程池的执行器,为每个任务创建一个新的虚拟线程

最后一种执行器值得一提:虚拟线程并不放入线程池。它们的开销非常小,因此为每个任务创建一个新的虚拟线程;为了限制资源使用,可以使用信号量,就像程序 [Threads15.kt] 中那样。还值得注意的是,协程库可以把执行器转换为“调度器”([executor.asCoroutineDispatcher()]):第 9 章的协程最终也是在线程池中运行的。

8.10.2. 带结果的任务:Callable 和 Future

方法 [execute] 向线程池传递一个 [Runnable],它不返回结果。[submit(task)] 方法还接受 [Callable<V>],这是一个函数式接口,其 [call(): V] 方法返回类型为 V 的结果(在 Java 中它声明了 [throws Exception];Kotlin 忽略这个声明)。它返回一个 [Future<V>] 对象,可以用来跟踪任务:

Future<V> 方法
作用
[get(): V]、[get(timeout: Long, unit: TimeUnit): V]
等待任务完成(最多等待 [timeout])并返回其结果。如果任务抛出异常,[get] 会抛出一个包装了该异常的 [ExecutionException] (属性 [cause])
[isDone(): Boolean]
指示任务是否已完成(正常完成、因异常或被取消);在 Kotlin 中,这是属性 [isDone]
[state(): Future.State]
(Java 19)任务的状态:[RUNNING]、[SUCCESS]、[FAILED]、或 [CANCELLED]
[resultNow(): V]、[exceptionNow(): Throwable]
(Java 19)已经完成的任务的结果或异常,无需等待
[cancel(mayInterruptIfRunning: Boolean): Boolean]
取消任务;如果任务已启动且 [mayInterruptIfRunning] 等于 [true],则执行它的线程被终止

执行器的 [invokeAll(collection of Callable)] 方法提交集合中的所有任务,等待它们全部完成,并按集合的顺序返回它们的 [Future] 值列表。[invokeAny] 方法返回第一个成功完成的任务的结果,并取消其他任务。程序 [Threads26.kt] 如下:

// ExecutorService:提交任务并通过 Future 获取其结果
package threads26

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.Callable
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.Future

fun main() {
    println("Main thread: ${Thread.currentThread()}")

    // 1 - 一个 2 个线程的线程池,在 use 块结束时自动关闭
    Executors.newFixedThreadPool(2).use { pool ->
        // 三个任务,各自返回一个 Int 类型的结果
        val futures: List<Future<Int>> = List(3) { number ->
            pool.submit<Int> {
                val name = Thread.currentThread().name
                println("${time()} : task $number runs in thread $name")
                // 工作
                Thread.sleep(500L * (number + 1))
                // 任务的结果
                number * 10
            }
        }
        // 结果:get() 等待任务结束
        futures.forEachIndexed { i, future ->
            try {
                println("task $i: result ${future.get()}, state ${future.state()}")
            } catch (e: ExecutionException) {
                println("task $i in error: ${e.cause}")
            }
        }

        // 一个抛出异常的任务
        val failed = pool.submit<Int> { fail() }
        try {
            failed.get()
        } catch (e: ExecutionException) {
            // 任务的异常被包装在 ExecutionException 中
            val cause = e.cause!!
            println("${e::class.simpleName} containing ${cause::class.simpleName} : ${cause.message}")
        }
        println("task in error: state ${failed.state()}")
    }

    // 2 - 每个任务一个虚拟线程;invokeAll 提交一组任务并等待它们结束
    Executors.newVirtualThreadPerTaskExecutor().use { executor ->
        val jobs = List(3) { number ->
            Callable {
                Thread.sleep(300)
                "job $number executed by ${Thread.currentThread()}"
            }
        }
        for (future in executor.invokeAll(jobs)) {
            // 任务已完成:resultNow() 无需等待即可返回其结果
            println(future.resultNow())
        }
    }
}

// 失败任务的工作
fun fail(): Int = throw IllegalStateException("test....")

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

说明:

  • 第 15 行:由 [Executors.newFixedThreadPool(2)] 创建的 2 个线程的线程池,并在 [use] 块结束时关闭;
  • 第 17–24 行:每个任务是一个 lambda,它显示执行它的线程,休眠 0.5、1 或 1.5 秒,然后返回一个整数结果——其最后一个表达式的值。函数 [List] 构造由 [Future<Int>] 对象 组成的列表,这三个对象由 [submit] 返回;
  • 第 18 行:请注意 submit 的重载。*[submit] 方法有多个版本,包括 ***[submit(Runnable)] 和 ***[submit(Callable<T>)]***。对于 lambda,如果 lambda 返回一个值,Java 会选择 [Callable] 版本。而 Kotlin 则把任何 lambda 都视为可转换为 [Runnable]* (此时其值被忽略),并选择 [submit(Runnable)]!如果你写 ***[val f = pool.submit { 10 }],编译器只会发出一个警告:
warning: expression is unused.

而 [f.get()] 产生 [null],即 [Runnable] 的“结果”。我们可以通过指定类型参数来强制使用 [Callable] 版本,即 [submit<Int> { … }](如这里所示),或者显式创建一个 [Callable]:[pool.submit(Callable { … })]。第 22 行的 [Thread.sleep] 不需要用 [try] 包围:Kotlin 没有受检异常,任何可能的 [InterruptedException] 都会记录在 [Future] 中;

  • 第 28 行:函数 [forEachIndexed] 遍历列表,同时返回索引和元素;
  • 第 30 行:[future.get()] 等待任务结束并返回其结果;[future.state()] 返回其状态。由于 [state] 不是 [getXxx] 形式的访问器,Kotlin 把它当作方法,而不是属性;
  • 第 37 行:一个执行函数 [fail] (第 64 行)的任务,该函数会抛出异常。[fail] 的返回类型是 [Int]:表达式 [throw …] 的类型是 [Nothing],它与所有类型兼容;
  • 第 39–43 行:任务中抛出的异常不会丢失;它被存储在 [Future] 对象中,然后在请求结果的线程中重新抛出,被包装在一个 *[ExecutionException] 中,其属性 [cause]*(Java 方法 *[getCause]*)包含原始异常。该属性的类型是 [Throwable?];运算符 [!!] 断言它不是 [null],这里可以保证这一点。表达式 [e::class.simpleName] 给出异常类的简短名称;
  • 第 49–58 行:一个为每个任务创建一个虚拟线程的执行器。任务被显式创建为 [Callable],使用 SAM 构造函数 [Callable { … }] (第 51 行):因此列表 [jobs] 的类型是 [List<Callable<String>>]。方法 [invokeAll] (第 56 行)将这三个作业分配给执行器并等待它们结束。任务完成后,[resultNow] 立即返回它们的结果。

结果:

> gradlew -q run -Pmain=threads26.Threads26Kt
Main thread: Thread[#3,main,5,main]
13:01:08.772 : task 0 runs in thread pool-1-thread-1
13:01:08.769 : task 1 runs in thread pool-1-thread-2
13:01:09.291 : 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....
task in error: state FAILED
job 0 executed by VirtualThread[#24]/runnable@ForkJoinPool-1-worker-1
job 1 executed by VirtualThread[#27]/runnable@ForkJoinPool-1-worker-2
job 2 executed by VirtualThread[#29]/runnable@ForkJoinPool-1-worker-2
  • 任务在线程池的线程中运行([pool-1-thread-1] 和 [pool-1-thread-2]);
  • 任务 2 直到任务 0 结束后才启动,使用的是任务 0 释放出来的线程:线程池只有 2 个线程,任务 2 在队列中等待。这种行为是可重现的;
  • 结果是在任务结束之后获取的,它们的状态是 [SUCCESS];
  • 失败任务的异常被主线程捕获,该任务的状态是 [FAILED];
  • 第二部分中的三个作业由三个不同的虚拟线程执行,这些虚拟线程挂载在载体线程 [ForkJoinPool-1-worker-1] 和 [ForkJoinPool-1-worker-2] 上(在载体之间的分配每次执行都不同)。

在 [get] 中阻塞线程来等待结果很简单,但这样就无法在不等待的情况下把处理操作链接到任务的完成上。下一章将介绍 JDK 的 [CompletableFuture] 类,它可以做到这一点;更重要的是介绍 Kotlin 的解决方案:协程,以及 [async] 和 [Deferred] (相当于 [Future] ,其结果通过 [await] 等待,而不会阻塞线程)。最后请注意,Java 25 以预览形式提供了 结构化并发 ([StructuredTaskScope]),它把一组子任务视为一个单一的工作单元(如果其中一个失败,其他任务会被取消)。本课程不使用它:Kotlin 协程基于同样的原则,而这一原则早已是 Kotlin 的标准特性,第 9 章将对此进行深入讲解。

8.11. 数据并行

8.11.1. 并行流

让我们回到线程的主要用途:为耗时的计算利用所有处理器。Kotlin 标准库没有提供对集合的并行操作:它的函数([filter]、[map]、[count]…)及其序列都是顺序的。不过,Kotlin 程序可以使用 Java 的 Stream API(第 5 章),其流可以 并行执行:只需在流上调用 [parallel()] ,或者在集合上调用 [parallelStream()] 而不是 [stream()] (Kotlin 的列表是 [java.util.List]:它具有这些方法)。流随后把数据分成若干块,由多个线程处理这些块,再合并部分结果。所使用的线程来自 共享池 ([ForkJoinPool.commonPool()]),再加上执行该流的线程。默认情况下,共享池的线程数等于处理器数减一:调用线程自己也参与计算。

只有当对每个元素的处理 独立于 其他元素时,这些流才适用:处理顺序是不确定的,如果处理过程要更新共享数据,就必须对其加以保护。程序 [Threads27.kt] 如下:

// 并行流:IntStream.parallel 和 parallelStream
package threads27

import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ForkJoinPool
import java.util.stream.IntStream
import kotlin.time.measureTimedValue

fun main() {
    // 1 - 统计小于 N 的素数个数
    val N = 5_000_000
    // 顺序版本:for 循环
    val (nbLoop, durationLoop) = measureTimedValue {
        var nb = 0
        for (i in 2..<N) {
            if (isPrime(i)) nb++
        }
        nb
    }
    display("sequential for", nbLoop.toLong(), durationLoop.inWholeMilliseconds)

    // 顺序版本:Kotlin 对区间的 count 函数
    val (nbKotlin, durationKotlin) = measureTimedValue { (2..<N).count { isPrime(it) } }
    display("sequential count", nbKotlin.toLong(), durationKotlin.inWholeMilliseconds)

    // 顺序版本:Java 流
    val (nbStream, durationStream) = measureTimedValue { IntStream.range(2, N).filter { isPrime(it) }.count() }
    display("sequential stream", nbStream, durationStream.inWholeMilliseconds)

    // 并行版本:同一个流,改为并行
    val (nbParallel, durationParallel) = measureTimedValue {
        IntStream.range(2, N).parallel().filter { isPrime(it) }.count()
    }
    display("parallel stream", nbParallel, durationParallel.inWholeMilliseconds)

    // 参与工作的线程以及每个线程找到的素数个数
    val threads = ConcurrentHashMap<String, Int>()
    IntStream.range(2, N).parallel()
        .filter { isPrime(it) }
        .forEach { threads.merge(Thread.currentThread().name, 1, Int::plus) }
    for ((name, nb) in threads.toSortedMap()) {
        println("  thread %-30s : %,d prime numbers found".format(name, nb))
    }

    // 2 - 并行处理一个集合
    val files = listOf("a.txt", "b.txt", "c.txt", "d.txt", "e.txt")
    files.parallelStream().forEach { file ->
        println("${time()} : processing of $file in thread ${Thread.currentThread().name}")
        // 模拟处理
        sleep(500)
    }
    println("parallel forEach finished")
    println("Parallelism of the common pool: ${ForkJoinPool.getCommonPoolParallelism()}")
}

// 显示结果及其耗时
fun display(method: String, nb: Long, ms: Long) {
    println("%-20s : %,d prime numbers in %d ms".format(method, nb, ms))
}

// 素性测试(刻意写得很简单)
fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    var d = 2
    while (d * d <= n) {
        if (n % d == 0) return false
        d++
    }
    return true
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 当前时间,精确到毫秒
fun time(): String = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))

说明:

  • 第 15–22 行:使用标准的 [for] 循环统计小于 5,000,000 的素数。函数 [isPrime] (第 64–71 行)测试不超过该数平方根的除数:这是一个耗时的过程,并且各次迭代相互独立。耗时由 [measureTimedValue] 函数(标准库 [kotlin.time] 包)测量:它执行其 lambda,并返回一个 [TimedValue] 对象,其中包含 lambda 返回的值和执行的耗时(一个 *[Duration]*);它被解构为两个变量。属性 *[inWholeMilliseconds] 以毫秒为单位给出耗时。Java 使用 ***[System.nanoTime()]** 来测量耗时;
  • 第 25 行:同样的计算,以 Kotlin 风格书写:函数 [count] 作用于区间 [2..<N] ,统计满足谓词的元素个数。这是顺序执行的;
  • 第 29 行:使用顺序 Java 流进行同样的计算:[IntStream.range(2, N)] 生成从 2 到 N - 1 的整数,[filter] 只保留素数,[count] 对它们计数(结果是一个 [Long])。lambda [{ isPrime(it) }] 被转换为 [IntPredicate],即 [filter] 所期望的函数式接口;
  • 第 33–34 行:同样的流,通过 [parallel()] 变成并行的。其他地方无需任何改动:每个线程统计它所负责的数据段中的素数,流再把各部分的计数相加。线程之间不共享任何数据;
  • 第 39–44 行:为了确定哪些线程完成了工作,并行流为每个线程统计它找到的素数,并存储在一个共享的 [ConcurrentHashMap] 中。这是共享数据,通过原子操作([merge])更新;
  • 第 48–52 行:Kotlin 文件名列表的 [parallelStream()] 方法返回一个并行流;[forEach] 处理每个文件(处理过程用半秒的暂停来模拟)。对于并行流,[forEach] 不保持列表的顺序;[forEachOrdered] 会保持顺序,但会牺牲一些并行性;
  • 第 55 行:共享池中的线程数;
  • 第 59–60 行:显示结果:[%-20s] 将方法名左对齐到 20 个字符。

结果:

> gradlew -q run -Pmain=threads27.Threads27Kt
sequential for       : 348,513 prime numbers in 2523 ms
sequential count     : 348,513 prime numbers in 1891 ms
sequential stream    : 348,513 prime numbers in 3697 ms
parallel stream      : 348,513 prime numbers in 4583 ms
  thread ForkJoinPool.commonPool-worker-1 : 224,082 prime numbers found
  thread main                           : 124,431 prime numbers found
12:56:50.425 : processing of b.txt in thread ForkJoinPool.commonPool-worker-1
12:56:50.440 : processing of c.txt in thread main
12:56:50.943 : processing of e.txt in thread main
12:56:50.955 : processing of a.txt in thread ForkJoinPool.commonPool-worker-1
12:56:51.451 : processing of d.txt in thread main
parallel forEach finished
Parallelism of the common pool: 1
  • 四个版本找到的素数个数相同;
  • 有两个线程参与了并行处理:线程 [main] 和共享池中唯一的线程([ForkJoinPool.commonPool-worker-1]):在这台双处理器机器上,共享池只有一个线程(最后一行);
  • 文件两个一组地被处理,每组相隔半秒,处理顺序与列表顺序不一致;
  • 这里,并行流并不比顺序版本更快,实际上还是最慢的。这并不是并行处理的缺陷:测试时,这台机器(2 个处理器)正在运行许多其他非常活跃的程序(平均有大约十个线程处于就绪状态,等待 2 个处理器运行),因此并行处理所依赖的第二个处理器无法使用。所有版本测得的执行时间每次运行之间也有显著差异。在负载较轻、有 n 个处理器的机器上,这样的并行线程可以比顺序线程快近 n 倍。在得出结论之前,始终需要在真实条件下测量性能:并行化是有代价的(工作划分、同步、结果合并),只有在处理每个元素需要足够多的计算,并且有处理器可供执行时,这些代价才值得。

在下一章中,我们还将使用协程并行化计算,在 [Dispatchers.Default] 调度器上启动它们,该调度器的线程数同样与处理器数相等。

8.11.2. 分而治之:ForkJoinPool 和 RecursiveTask

并行流基于 Fork/Join框架(Java 7),该框架也可以直接使用。它非常适合“分而治之”算法:过大的任务被分解为子任务,子任务又继续分解,直到各部分小到可以直接处理;然后合并子任务的结果。任务是派生自 [RecursiveTask<V>] (返回类型为 V 的结果的任务)或 [RecursiveAction] (无结果)的类,需要重写其 [compute] 方法。在 [compute] 中,子任务的 [fork()] 方法立即将其提交到线程池,其 [join()] 方法等待其结果。

任务由 [ForkJoinPool] 执行,其中每个线程都有自己的任务队列。无事可做的线程会从另一个线程的队列中“窃取”任务(“工作窃取”):负载因此被自动分配。承载虚拟线程的线程也构成一个 [ForkJoinPool]:这就是我们在虚拟线程的文本表示中看到的那个([ForkJoinPool-1-worker-1])。程序 [Threads28.kt] 使用递归任务统计素数:

// 分而治之:ForkJoinPool 和 RecursiveTask
package threads28

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveTask
import kotlin.time.measureTimedValue

fun main() {
    val N = 5_000_000
    // 公共池,并行流默认使用
    val (nb, duration) = measureTimedValue { ForkJoinPool.commonPool().invoke(CountPrimes(2, N)) }
    println("common pool       : %,d prime numbers in %d ms".format(nb, duration.inWholeMilliseconds))

    // 一个 4 个线程的线程池,在 use 块结束时关闭
    ForkJoinPool(4).use { pool ->
        CountPrimes.chunks.clear()
        val (nb4, duration4) = measureTimedValue { pool.invoke(CountPrimes(2, N)) }
        println("pool of 4 threads : %,d prime numbers in %d ms".format(nb4, duration4.inWholeMilliseconds))
        println("tasks stolen by one thread from another: ${pool.stealCount}")
    }
    // 各数据块在上一个线程池的线程间的分布
    for ((name, nbChunks) in CountPrimes.chunks.toSortedMap()) {
        println("  %-25s : %d chunks processed".format(name, nbChunks))
    }
}

// 一个统计区间 [start, end[ 内素数个数的任务
class CountPrimes(private val start: Int, private val end: Int) : RecursiveTask<Int>() {
    companion object {
        // 低于此阈值时,直接处理该数据块
        const val THRESHOLD = 100_000
        // 每个线程处理的数据块数量
        val chunks = ConcurrentHashMap<String, Int>()
    }

    override fun compute(): Int {
        // 数据块足够小:按顺序处理
        if (end - start <= THRESHOLD) {
            chunks.merge(Thread.currentThread().name, 1, Int::plus)
            return (start..<end).count { isPrime(it) }
        }
        // 否则,将其一分为二
        val middle = (start + end) ushr 1
        val left = CountPrimes(start, middle)
        val right = CountPrimes(middle, end)
        // 左半部分交给线程池(另一个线程可能会"窃取"它)
        left.fork()
        // 右半部分由当前线程处理
        val nbRight = right.compute()
        // 我们等待左半部分的结果,并合并两个结果
        return left.join() + nbRight
    }
}

// 素性测试(刻意写得很简单)
fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    var d = 2
    while (d * d <= n) {
        if (n % d == 0) return false
        d++
    }
    return true
}

说明:

  • 第 29–52 行:任务 [CountPrimes] 统计区间 [start, end[ 中的素数。它派生自 [RecursiveTask<Int>]:Java 类是抽象的;它的无参构造函数([RecursiveTask<Int>()])在类头中被调用。边界 [start] 和 [end] 是在主构造函数中声明的私有属性;
  • 第 30–34 行:类的成员被组织在伴生对象中:阈值 [THRESHOLD] (少于 100,000 个数的区间直接处理),以及每个线程已处理的块数([chunks])。Fork/Join 任务是可序列化的;Java 声明了一个序列化版本号([serialVersionUID]),这是其编译选项 [-Xlint:all] 所要求的。Kotlin 编译器不要求它,而且我们绝不会序列化这些任务:因此省略它;
  • 第 37 行:重写方法 [compute],它在 Java 中声明为 [protected] :重写后的方法仍然是 [protected] ,无需我们指定;
  • 第 39–41 行:相对较小的块由区间内的函数 [count] 按顺序处理;
  • 第 44–46 行:过大的块被拆分为两个子任务。表达式 [(start + end) ushr 1] 使用无符号右移计算中点(中缀函数 [ushr],对应 Java 运算符 [>>>]),这样可以防止和超出 [Int] 的容量时发生溢出;
  • 第 48 行:左半部分被放入线程池:另一个线程可能会取走它;
  • 第 50 行:右半部分由当前线程通过直接调用 [compute] 来处理。没有必要把两半都交给线程池:那样当前线程就只能干等着;
  • 第 52 行:线程等待左半部分的结果(如果没有人“窃取”它,线程将自己处理),并合并两个结果;
  • 第 12 行:任务首先由共享池执行。[invoke(task)] 方法提交任务并等待其结果;
  • 第 16–20 行:然后由一个 4 线程的线程池执行,该线程池在 [use] 块中使用([ForkJoinPool] 是一个 [ExecutorService])。[stealCount] 属性(Java 方法 [getStealCount])返回一个线程从另一个线程窃取的任务数;
  • 第 23–24 行:该线程池中各线程所处理块的分布。

结果:

1
2
3
4
5
6
7
8
> gradlew -q run -Pmain=threads28.Threads28Kt
common pool       : 348,513 prime numbers in 3638 ms
pool of 4 threads : 348,513 prime numbers in 2568 ms
tasks stolen by one thread from another: 6
  ForkJoinPool-1-worker-1   : 13 chunks processed
  ForkJoinPool-1-worker-2   : 16 chunks processed
  ForkJoinPool-1-worker-3   : 14 chunks processed
  ForkJoinPool-1-worker-4   : 21 chunks processed
  • 共享池并不比顺序循环更快(与前一个程序比较):在这台机器上,它只有一个线程,而主线程——在 [invoke] 中等待结果——并不像在并行流中那样参与计算;
  • 4 线程的线程池更快,因为它能同时使用两个处理器,但并没有快一倍,因为机器仍然被其他程序占用了大量负载。线程数多于处理器数对纯计算没有好处,但在这里代价也不大;
  • 64 个块(5,000,000 / 100,000,因为对半拆分而向上取整到 2 的幂)通过任务窃取分配给了 4 个线程。这种分配与执行时间一样,每次运行都不同;块的数量和计算结果是可重现的。

并行流在大多数情况下已经足够;只有对于难以用流轻松表达的递归算法(排序、树遍历等),才需要编写 Fork/Join 任务。

8.12. 线程局部数据

8.12.1. 原理

考虑一个三层应用程序:

Image

假设该应用程序是多用户的,例如 Web 应用程序。每个用户请求由一个线程处理。线程的生命周期如下:

  • 创建线程(虚拟线程)或从线程池中请求一个线程来满足用户的请求;
  • 如果该请求需要数据,线程会执行 [ui] 层的一个函数,该函数调用 [business] 层的一个函数,后者又调用 [dao] 层的一个函数;
  • 线程向用户返回响应。随后它要么终止,要么被归还给线程池。

在第二步中,让线程拥有自己的数据——即不与其他线程共享的数据——可能会很有用。例如,这些数据可以属于该线程所服务的特定用户,并在各个 [ui, business, dao] 层中使用,而不必作为参数传递给每个函数。

JDK 为此提供了两种工具,Kotlin 原样使用它们:

  • [ThreadLocal<T>] 类(Java 1.2):这是一个对象,其值——通过 [get()] 读取,通过 [set(value)] 写入——对每个线程都不同。构造函数 [ThreadLocal.withInitial(factory)] 为每个线程提供初始值;方法 [remove()] 清除当前线程的值。派生类 [InheritableThreadLocal<T>] 把创建线程的值传递给新创建的线程;
  • [ScopedValue<T>] 类(在 Java 25 中为正式特性):一个在有限的代码范围内绑定到线程的值,在该范围内不能被修改。

8.12.2. ThreadLocal 类

程序 [Threads29.kt] 比较了一个普通属性、一个 [ThreadLocal]、和一个 [InheritableThreadLocal]:

// 线程局部数据:ThreadLocal 和 InheritableThreadLocal
package threads29

import kotlin.concurrent.thread

// 程序的数据
object Context {
    // 一个普通(volatile)属性:只有一个副本,由所有线程共享
    @Volatile
    var shared = 0
    // 每个线程一个副本;初始值为 null
    val perThread = ThreadLocal<Int?>()
    // 每个线程一个副本,由提供的工厂为每个线程初始化
    val user: ThreadLocal<String> =
        ThreadLocal.withInitial { "anonymous (thread ${Thread.currentThread().name})" }
    // 每个线程一个副本,其初始值继承自创建它的线程
    val language = InheritableThreadLocal<String?>()
}

fun main() {
    Thread.currentThread().name = "Main"
    // 主线程写入自己的值
    Context.shared = 100
    Context.perThread.set(100)
    Context.user.set("admin")
    Context.language.set("fr")

    // 三个线程写入后再次读取数据
    val threads = List(3) { number ->
        thread(name = "T$number") {
            // 写入
            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()
        }
    }
    threads.forEach { it.join() }
    // 主线程再次读取
    display()
}

// 显示当前线程看到的数据
fun display() {
    println("%-4s : shared=%-3d perThread=%-3d user=%-20s language=%s".format(
        Thread.currentThread().name, Context.shared, Context.perThread.get(),
        Context.user.get(), Context.language.get()))
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

说明:

  • 第 9–10 行:[Context] 对象的一个普通属性。它只有一个实例,由所有线程共享。它带有 [@Volatile],以便每个线程都能看到其他线程写入的最新值;
  • 第 12 行:一个 [ThreadLocal<Int?>] 对象。每个线程都有自己的值;只要线程还没有写入,[get] 就返回 [null]。我们声明值的类型为 [Int?],以便编译器知道 [get] 可能产生 [null]:如果使用 [ThreadLocal<Int>],Kotlin 会把 *[get]* 的结果视为平台类型(***[Int!]***),对其不做任何检查;
  • 第 14–15 行:由 [ThreadLocal<String>] 对象通过 [ThreadLocal.withInitial { … }] 创建。传给该方法的 lambda(被转换为 [Supplier])在线程第一次读取值而尚未写入时执行;它为该线程提供初始值。这里,[get] 永远不会返回 [null]:因此类型 [String] 是合理的。Kotlin 还提供了一个扩展函数 [getOrSet { … }] (包 [kotlin.concurrent]),它返回当前线程的值,如果该值为 [null],则先用 lambda 初始化它;
  • 第 17 行:一个 [InheritableThreadLocal<String?>] 对象:线程创建时,其初始值是创建线程当时所持值的副本;
  • 第 23–26 行:主线程写入自己的值;
  • 第 32–40 行:每个线程写入自己的值,除了线程 T2(它不设置用户),以及线程 T1(它是唯一修改语言的线程);
  • 第 43 行:每个线程等待其他线程写入完毕,然后再次读取这些值;
  • 第 54–57 行:显示当前线程所看到的数据。格式 [%-3d] 接受值 [null],并将其显示为 [null]。

结果:

1
2
3
4
5
> gradlew -q run -Pmain=threads29.Threads29Kt
T0   : shared=1   perThread=0   user=user0                language=fr
T2   : shared=1   perThread=2   user=anonymous (thread T2) language=fr
T1   : shared=1   perThread=1   user=user1                language=en
Main : shared=1   perThread=100 user=admin                language=fr
  • 普通属性 [shared] 对所有线程具有相同的值:最后写入的值(在本次执行中是线程 T1 的值;另一次执行可能产生不同的值);
  • [perThread] 在每个线程中保留了该线程写入的值;
  • [user] 具有每个线程写入的值;没有写入过它的线程 T2 得到的是 [withInitial] 的 lambda 提供的初始值;
  • [language] 对于线程 T0 和 T2 等于 [fr] ,它们从主线程继承了该值,从未写入过它。线程 T1 把它改为 [en] ,仅对它自己生效:主线程和其他线程看不到这一变化;
  • 除了 [shared] 的值和前三行的顺序之外,这些结果都是可重现的。

使用 [ThreadLocal] 需要一些预防措施。线程的值只在该线程存在期间存在:使用线程池时,为某个请求服务的线程随后还会为其他请求服务,因此必须在每个请求结束时调用 [remove] ;否则,下一个请求会发现上一个请求留下的数据(而且内存永远不会被释放)。使用虚拟线程时,可以创建数百万个线程,每个线程都有自己的数据副本:[InheritableThreadLocal] 随后会把它的值复制到每一个线程中。最后,一个可以被线程内任何函数修改的值会使代码难以理解。[ScopedValue] 类避免了这些问题。

第 9 章的协程带来了一个特殊的问题:协程可以在一个线程中开始执行并在另一个线程中继续,而 *[ThreadLocal] 无法跟踪这种情况。为解决这个问题,协程库提供了 [asContextElement(value)] 这个 [ThreadLocal] 的扩展函数,它会在协程执行所在的每个线程中设置 [ThreadLocal] 的值;协程也有自己的上下文数据机制,即 协程上下文*。我们将在下一章讲解。

8.12.3. ScopedValue 类

[ScopedValue<T>] 值在一段代码的执行期间被 绑定 到某个值,这段代码称为它的 作用域:

  • [ScopedValue.newInstance()] 创建一个绑定值,通常存放在顶层属性或对象的属性中,该属性是只读的([val]);
  • [ScopedValue.where(sv, value).run(action)] 执行该操作(一个 [Runnable]),并将 [sv] 绑定到 [value]。当该操作——以及它调用的所有函数——在当前线程中执行时,[sv.get()] 返回 [value]。操作结束后,绑定随之消失:无需清理;
  • [ScopedValue.where(sv, value).call(op)] 对返回结果的操作做同样的事;
  • 在作用域内,该值不能被修改;它只能在嵌套作用域中被绑定到另一个值;
  • [isBound()] 指示该值是否在当前线程中已绑定(Kotlin 将其视为属性 [isBound]);[orElse(other)] 返回绑定的值,如果未绑定,则返回 [other]。在任何作用域之外,[get()] 会抛出 [NoSuchElementException] 异常。

自 Java 25 起,[ScopedValue] 类已成为正式特性:为 Java 25 编译的 Kotlin 程序无需任何特殊选项,也不会有警告。程序 如下:

// 绑定到作用域的值:ScopedValue(Java 25)
package threads30

// 代码代表其运行的用户
val USER: ScopedValue<String> = ScopedValue.newInstance()

fun main() {
    println("Outside any scope, is USER bound? ${USER.isBound}")
    try {
        USER.get()
    } catch (e: NoSuchElementException) {
        println("get() out of scope: ${e::class.simpleName}")
    }

    // 1 - 两个同时进行的处理,各自对应自己的用户
    val t1 = Thread.ofVirtual().start { ScopedValue.where(USER, "alice").run(::process) }
    val t2 = Thread.ofVirtual().start { ScopedValue.where(USER, "bob").run(::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")
        // 在作用域中创建的线程不会继承该绑定
        val child = Thread.ofVirtual().start { println("child thread: bound? ${USER.isBound}") }
        child.join()
    }

    // 3 - call:返回结果的带绑定的处理
    val message = ScopedValue.where(USER, "carole")
        .call<String, RuntimeException> { "hello ${USER.get()}" }
    println(message)
    // 离开作用域后,绑定消失
    println("After the scopes: bound? ${USER.isBound}, orElse: ${USER.orElse("nobody")}")
}

// [business] 层调用 [dao] 层,而不向其传递用户
fun process() {
    display("[business] layer")
    dao()
}

// [dao] 层在当前作用域中找到用户
fun dao() {
    display("[dao] layer")
}

// 显示当前作用域中绑定的用户
fun display(place: String) {
    println("$place : USER = ${USER.get()}")
}

说明:

  • 第 5 行:绑定值 [USER],一个只读的顶层属性。它的类型 [ScopedValue<String>] 是显式声明的:泛型方法 [newInstance] 无法推断它;
  • 第 8–12 行:在任何作用域之外,该值是未绑定的,[get] 会抛出异常。类 [NoSuchElementException] 无需导入:Kotlin 把它视为标准库类型的类型别名([kotlin.NoSuchElementException]);
  • 第 16–17 行:两个虚拟线程执行函数 [process],各自处于 [USER] 被绑定到不同用户的作用域中。函数引用 [::process] 被转换为 [Runnable];
  • 第 40–47 行:函数 [process] ([business] 层)调用函数 [dao] ([dao] 层),但没有把用户传给它:两者各自通过 [USER.get()] 获取用户(第 52 行);
  • 第 22–28 行:在 [USER] 等于 [admin] 的作用域中包含一个嵌套作用域(第 24 行),在其中它等于 [guest]。退出嵌套作用域后,我们又得到 [admin]。关于写法 [where(…).run { … }] 的一点说明:Kotlin 标准库中也有一个函数 [run],适用于任何对象([obj.run { … }])。这里被调用的确实是 [run] 方法(来自类 [ScopedValue.Carrier] )被调用,因为在 Kotlin 中成员方法总是优先于同名的扩展函数。结果证实了这一点:如果调用的是 Kotlin 函数 [run] ,就不会绑定任何值,而 [get] 就会抛出异常;
  • 第 27–28 行:在作用域内创建的线程看不到该绑定:与 *[InheritableThreadLocal]* 不同,[ScopedValue] 不会传递给由 *[Thread] 创建的线程。不过,它会传递给结构化并发([StructuredTaskScope]*,在 Java 25 中为预览特性)的子任务,结构化并发确保这些子任务在作用域结束前完成;
  • 第 32–33 行:[call] 在作用域内执行一个操作并返回其结果。它的参数类型为 [ScopedValue.CallableOp<T, X>],其中 [X] 是该操作可能抛出的异常类型(在 Java 中是受检异常)。Kotlin 无法从 lambda 推断 [X] (lambda 不声明任何异常);不给出类型参数时,编译器会报告:
error: cannot infer type for type parameter 'X'. Specify it explicitly.

因此我们指定 [call<String, RuntimeException>]:结果是一个 [String],并且该操作不会抛出受检异常;

  • 第 36 行:在这些作用域之后,该值不再绑定。

结果:

> gradlew -q run -Pmain=threads30.Threads30Kt
Outside any scope, is USER bound? false
get() out of scope: NoSuchElementException
[business] layer : USER = bob
[dao] layer : USER = bob
[business] layer : USER = alice
[dao] layer : USER = alice
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

第 3–6 行中来自虚拟线程的消息可能以不同的顺序出现(bob 在 alice 之前);其余部分是可重现的。[ScopedValue] 适合“向下”传递的上下文数据,即从调用者传给被调用函数:已认证用户、事务、区域设置等。当被调用的函数需要修改数据以供后续处理时,就需要使用 [ThreadLocal]。

8.12.4. 应用:跨层共享事务

考虑下面这个三层应用程序,其中 [dao] 层管理一个商品表:

Image

假设 [dao] 层的接口最初如下:

1
2
3
4
5
interface IDao {
    fun insertArticle(article: Article): Int
    fun getAllArticles(): List<Article>
    fun deleteAllArticles()
}

后来,出现了在一个 事务中插入一组商品的需求,因为要求是要么全部成功要么全部失败:要么所有商品都被插入,要么一个也不插入。可以在接口中添加函数 [insertArticles(articles: List<Article>)]。然后,对于另一个应用程序,又出现了在事务中删除一组商品的需求……为了满足不同的业务需求,[dao] 层会不断膨胀。我们可以采取另一种方法:

  • 在 [dao] 层中只包含基本操作(插入、更新、删除、读取一个商品);
  • 将同时更新多个商品的操作移到 [business] 层。这些操作使用 [dao] 层的基本操作。

这种方案的优点是,同一个 [dao] 层无需修改即可与不同的 [business] 层配合使用。它带来了一个挑战,即如何管理将需要原子执行的更新组合在一起的事务:

  • 事务必须由 [business] 层在调用 [dao] 层的函数之前发起;
  • [dao] 层中的函数必须知道事务的存在,才能参与其中;
  • 事务必须由 [business] 层完成(提交或回滚)。

为了让 [dao] 层的函数知道是否有正在进行的事务,可以把事务作为参数添加到 [dao] 层的每个函数中。这个参数随后会出现在接口函数的签名中,从而使接口与特定的数据源绑定。线程局部数据提供了更优雅的解决方案:[business] 层把事务放入线程局部数据,[dao] 层再从那里获取它。[dao] 层的函数签名无需更改。多个线程(多个用户)可以同时工作:每个线程有自己的事务。

数据库将在第 10 章和第 11 章中介绍。为了让重点放在线程上,这里我们使用内存中的表和模拟的事务。程序 [Threads31.kt] 把所有层合并在一个源文件中。实体如下:

// 一件商品
data class Article(
    val id: Int, val name: String, val price: Double, val currentStock: Int, val minimumStock: Int
)

// 一个模拟事务:它记录如何撤销每次更新
class Transaction {
    companion object {
        private val counter = AtomicInteger()
    }

    private val undos = ArrayDeque<() -> Unit>()
    val number = counter.incrementAndGet()

    // 记录撤销某次更新的操作
    fun log(undo: () -> Unit) {
        undos.addFirst(undo)
    }

    // 提交事务:保留更新
    fun commit() {
        undos.clear()
    }

    // 回滚事务:撤销更新,从最后一个到第一个
    fun rollback() {
        while (true) {
            val undo = undos.removeFirstOrNull() ?: break
            undo()
        }
    }
}

// 各层共享的线程局部数据
object ThreadContext {
    // 线程的当前事务(如果没有则为 null)
    val transaction = ThreadLocal<Transaction?>()
}
  • 第 2–3 行:商品是一个数据类,其标识符 [id] 由 [dao] 层设置;
  • 第 7–29 行:一个模拟的事务。在事务内进行的每次更新都会记录撤销它所需的操作(函数 [log]);[commit] 提交事务,同时忽略这些操作;[rollback] 通过从最后一个到第一个依次执行回滚操作来回滚事务。回滚操作是类型为 [() -> Unit] 的函数:在 Kotlin 中,函数类型取代了 Java 接口 [Runnable]。这些操作存放在一个栈中,这里是 Kotlin 标准库的 *[ArrayDeque] (*[kotlin.collections.ArrayDeque],自动导入):[addFirst] 函数压入栈顶,[removeFirstOrNull] 函数从栈顶弹出,如果栈为空则返回 [null] 。在 [rollback] 循环中,Elvis 运算符 [?: break] 在栈为空时退出循环;否则,弹出的操作由 [undo()] 执行。真正的数据库也以类似的方式工作,使用的是事务日志;
  • 第 8–13 行:每个事务都分配有一个唯一的编号,即只读属性 [number],在对象创建时计算。由于事务可能由多个线程同时创建,存放在伴生对象中的计数器是一个 [AtomicInteger],它以原子方式递增;
  • 第 35–37 行:跨层共享的线程局部数据:线程的当前事务,如果没有则为 [null] ,因此类型是 [ThreadLocal<Transaction?>]。

[dao] 层如下:

// [dao] 层:一个内存中的商品表,对名称有唯一性约束
interface IDao {
    fun insertArticle(article: Article): Int
    fun getAllArticles(): List<Article>
    fun deleteAllArticles()
}

class Dao : IDao {
    // 该表由所有线程共享,及其锁
    private val table = mutableListOf<Article>()
    private val lock = Any()
    private var nextId = 1

    override fun insertArticle(article: Article): Int {
        // 当前线程中是否有正在进行的事务?
        val transaction = ThreadContext.transaction.get()
        synchronized(lock) {
            check(table.none { it.name == article.name }) { "an article named [${article.name}] already exists" }
            val inserted = article.copy(id = nextId++)
            table += inserted
            // 在事务中,我们记录如何撤销插入
            transaction?.log {
                synchronized(lock) { table -= inserted }
            }
            val mode = if (transaction == null) "outside a transaction"
                       else "in transaction ${transaction.number}"
            val name = Thread.currentThread().name
            println("[$name] [dao] insertion of ${inserted.name} (id ${inserted.id}) $mode")
            return 1
        }
    }

    override fun getAllArticles(): List<Article> = synchronized(lock) { table.toList() }

    override fun deleteAllArticles() {
        synchronized(lock) { table.clear() }
    }
}
  • 第 10–11 行:商品表,由所有线程共享。对它的访问由第 11 行的锁保护;
  • 第 16 行:函数 [insertArticle] 获取 [business] 层放入 当前线程的局部数据中的事务(如果有的话)。它的变量 [transaction] 的类型是 [Transaction?];
  • 第 18 行:该表对商品名称有唯一性约束:插入名称已存在的商品会抛出异常。Kotlin 函数 [check] (第 3 章)在条件为假时抛出 [IllegalStateException],消息由 lambda 计算;函数 [none] 验证表中没有元素满足该谓词;
  • 第 19–20 行:插入的记录是所收到记录的副本,其标识符由 [dao] 层分配。由于只读数据类不能被修改,因此使用 [copy] 函数创建一个新对象,它只改变指定名称的属性;
  • 第 22–23 行:如果存在事务,[dao] 层就通过记录如何撤销该插入来参与其中。安全调用 [?.] 仅当 [log] 所作用的 [transaction] 不等于 [null] 时才调用它。作为尾随 lambda 传入的回滚 lambda 捕获了变量 [inserted];
  • 第 25–28 行:跟踪输出显示线程、插入的记录以及事务(如果有)。在 [else] 分支中,编译器知道 [transaction] 不是 [null] (智能转换);
  • 第 33 行:返回的商品列表是表的副本([table.toList()]),这样调用者在遍历它时,不会受到另一个线程同时修改的影响。函数 [synchronized] 返回其代码块的值。

[business] 层如下:

// [business] 层
interface IBusiness {
    fun insertArticlesInTransaction(articles: List<Article>)
    fun insertArticlesOutOfTransaction(articles: List<Article>)
    fun getAllArticles(): List<Article>
    fun deleteAllArticles()
}

class Business(private val dao: IDao) : IBusiness {
    // 插入一个商品列表:要么全部成功,要么全部失败
    override fun insertArticlesInTransaction(articles: List<Article>) {
        val name = Thread.currentThread().name
        // 事务开始,存储在线程局部数据中
        val transaction = Transaction()
        ThreadContext.transaction.set(transaction)
        try {
            for (article in articles) {
                // [dao] 层将在线程中找到该事务
                dao.insertArticle(article)
                // 模拟处理,给其他线程介入的时间
                sleep(200)
            }
            transaction.commit()
            println("[$name] [business] transaction ${transaction.number} committed")
        } catch (e: RuntimeException) {
            transaction.rollback()
            println("[$name] [business] transaction ${transaction.number} rolled back")
            // 异常被重新抛给调用者
            throw e
        } finally {
            // 线程不再有正在进行的事务
            ThreadContext.transaction.remove()
        }
    }

    // 不使用事务插入一个商品列表
    override fun insertArticlesOutOfTransaction(articles: List<Article>) {
        articles.forEach(dao::insertArticle)
    }

    override fun getAllArticles(): List<Article> = dao.getAllArticles()

    override fun deleteAllArticles() = dao.deleteAllArticles()
}
  • 第 9 行:[dao] 层通过主构造函数注入,这使它成为一个私有属性;
  • 第 14–15 行:函数 [insertArticlesInTransaction] 启动一个事务,并把它保存在线程的局部数据中;
  • 第 19 行:对每个商品调用 [dao] 层的插入函数,而不向它传递事务;
  • 第 21 行:一次暂停模拟处理过程,以便让另一个线程有时间在事务期间介入(测试程序的第三部分);
  • 第 23 行:如果程序执行到这里,说明没有发生异常:事务被提交;
  • 第 25–29 行:如果发生异常,事务被回滚,并把异常重新抛给调用者;
  • 第 32 行:在任何情况下,线程都不再有活动的事务:[remove()] 清除线程的值。如果线程会被重用(池化线程),这一点至关重要;
  • 第 37–38 行:同样的插入,但不使用事务。绑定引用 [dao::insertArticle] 指向函数 [insertArticle] ,它属于对象 [dao];
  • 最后两个函数把工作委托给 [dao] 层,函数体精简为单个表达式。

测试程序如下:

fun main() {
    // 应用程序的各层
    val dao: IDao = Dao()
    val business: IBusiness = Business(dao)
    Thread.currentThread().name = "Main"

    // 两个同名商品:第二个违反了名称的唯一性约束
    val articles = listOf(Article(0, "article", 100.0, 10, 1), Article(0, "article", 100.0, 10, 1))

    // 1 - 在事务之外插入
    println("Inserting the articles outside a transaction...")
    execute { business.insertArticlesOutOfTransaction(articles) }
    displayArticles(business)

    // 2 - 在事务中插入
    business.deleteAllArticles()
    println("Inserting the articles in a transaction...")
    execute { business.insertArticlesInTransaction(articles) }
    displayArticles(business)

    // 3 - 两个同时运行的线程:线程 A 的事务对线程 B 不可见
    business.deleteAllArticles()
    println("Two simultaneous threads...")
    val articlesA = listOf(Article(0, "keyboard", 20.0, 5, 1), Article(0, "mouse", 10.0, 5, 1),
        Article(0, "keyboard", 20.0, 5, 1))
    val articlesB = listOf(Article(0, "screen", 150.0, 2, 1))
    val threadA = thread(name = "A") { execute { business.insertArticlesInTransaction(articlesA) } }
    Thread.sleep(100)
    val threadB = thread(name = "B") { execute { business.insertArticlesOutOfTransaction(articlesB) } }
    threadA.join()
    threadB.join()
    displayArticles(business)
}

// 执行一个操作,如有异常则显示该异常
fun execute(action: () -> Unit) {
    try {
        action()
    } catch (e: RuntimeException) {
        println("[${Thread.currentThread().name}] ${e::class.simpleName} : ${e.message}")
    }
}

// 休眠 [ms] 毫秒
fun sleep(ms: Long) {
    try {
        Thread.sleep(ms)
    } catch (_: InterruptedException) {
        Thread.currentThread().interrupt()
    }
}

// 显示商品列表
fun displayArticles(business: IBusiness) {
    println("List of articles:")
    for (article in business.getAllArticles()) {
        println("  $article")
    }
}
  • 第 8 行:创建一个包含两个同名商品的列表。第二个商品的插入将被拒绝。如果在事务之外执行插入,第一个商品被插入并保留在列表中。如果在事务内执行,第一个商品被插入,然后在事务回滚时被移除;
  • 第 11–13 行:在事务之外插入该列表,然后显示表;
  • 第 16–19 行:与上面相同,但在事务内进行;
  • 第 22–31 行:两个线程同时运行。线程 A 在事务内插入三个商品(第三个违反唯一性约束);与此同时,十分之一秒后启动的线程 B 在事务之外插入一个商品;
  • 第 36–40 行:函数 [execute] 执行一个类型为 [() -> Unit] 的操作,并显示任何异常,前面加上线程名称。它以尾随 lambda 的方式调用:[executer { … }]。

结果:

> gradlew -q run -Pmain=threads31.Threads31Kt
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)
  • 在事务之外的插入把第一条记录留在了表中(第 5 行)。为数据类生成的 [toString] 函数会显示其每个属性的名称和值;
  • 在事务内执行的插入没有在表中留下任何商品:ID 为 2 的商品被回滚移除了;
  • 在第三部分中,线程 B 在线程 A 的事务 2 进行期间插入了显示器:它是 在事务之外进行的,因为事务是线程 A 的局部变量。事务 2 的回滚移除了 A 插入的键盘和鼠标,但没有移除 B 插入的显示器。这个结果是可重现的。

8.12.5. 结论

前面的例子展示了线程局部数据在事务管理中的价值。它不应被完全照搬,但它准确地描述了框架的工作方式:Spring 的事务管理([@Transactional] 注解)把事务和数据库连接放入 [ThreadLocal] 中,数据访问层查询它们,而代码无需自己操作事务;Hibernate 同样可以把工作会话与当前线程关联起来。我们将在第 11 章再讨论这些工具。在新的代码中,特别是使用虚拟线程时,推荐使用 *[ScopedValue]* 来传递这类上下文信息;使用协程时,这一角色由协程上下文承担(第 9 章)。

8.13. 延伸阅读

线程同步是一个具有挑战性的领域。本章介绍了主要的工具;如需深入了解:

  • Brian Goetz 等人的著作 [Java Concurrency in Practice] (Addison-Wesley),尽管它早于虚拟线程,但仍然是该主题的权威参考。它的示例是用 Java 写的,但它所讲的一切都适用于 JVM 上的 Kotlin;
  • Oracle Java 教程的“并发”部分:Lesson: Concurrency——它虽然陈旧,但对基础内容仍然准确;
  • [java.util.concurrent] 包的文档:Package java.util.concurrent,其中“Memory Consistency Properties”一节总结了“先于”(happens-before)关系;
  • Kotlin 标准库中 [kotlin.concurrent] 包的文档([thread]、[withLock]、[read]、[write]、[getOrSet]…):kotlin.concurrent;
  • 引入虚拟线程和作用域值的 Java 改进提案(JEP):JEP 444: Virtual Threads 和 JEP 506: Scoped Values。

在现代代码中,很少直接操作对象([Thread])。在 Java 中,我们更倾向于使用执行器([ExecutorService])、用于计算的并行流,以及用于涉及等待的任务的虚拟线程。Kotlin 拥有所有这些工具,但它还提供了自己的解决方案,将在下一章介绍:协程。协程是一种可以自行挂起(在网络访问、数据库访问或文件访问期间)而不阻塞执行它的线程的任务,之后可以恢复执行,并且可能在另一个线程中恢复;结构化并发确保没有协程被遗忘,并且错误和取消能正确传播。尽管如此,本章的概念仍然至关重要:协程在线程中运行,它们共享的数据必须使用相同的工具(锁、原子类、并发集合)来保护,或使用适用于协程的对应工具([Mutex]、[Channel]…)。