**目錄**
[TOC]
## 協程上下文與調度器
協程總是運行在一些以[CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/) 類型為代表的上下文中,它們被定義在了 Kotlin 的標準庫里。
協程上下文是各種不同元素的集合。其中主元素是協程中的 [Job](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html),我們在前面的文檔中見過它以及它的調度器,而本文將對它進行介紹。
### 調度器與線程
協程上下文包含一個 _協程調度器_ (參見 [CoroutineDispatcher](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/index.html))它確定了哪些線程或與線程相對應的協程執行。協程調度器可以將協程限制在一個特定的線程執行,或將它分派到一個線程池,亦或是讓它不受限地運行。
所有的協程構建器諸如 [launch](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html) 和 [async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 接收一個可選的[CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/) 參數,它可以被用來顯式的為一個新協程或其它上下文元素指定一個調度器。
嘗試下面的示例:
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
launch { // 運行在父協程的上下文中,即 runBlocking 主協程
println("main runBlocking : I'm working in thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) { // 不受限的——將工作在主線程中
println("Unconfined : I'm working in thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) { // 將會獲取默認調度器
println("Default : I'm working in thread ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("MyOwnThread")) { // 將使它獲得一個新的線程
println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
}
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-01.kt)獲取完整代碼。
它執行后得到了如下輸出(也許順序會有所不同):
```text
Unconfined : I'm working in thread main
Default : I'm working in thread DefaultDispatcher-worker-1
newSingleThreadContext: I'm working in thread MyOwnThread
main runBlocking : I'm working in thread main
```
當調用 `launch { …… }` 時不傳參數,它從啟動了它的 [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html)中承襲了上下文(以及調度器)。在這個案例中,它從 `main` 線程中的 `runBlocking`主協程承襲了上下文。
[Dispatchers.Unconfined](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-unconfined.html) 是一個特殊的調度器且似乎也運行在 `main` 線程中,但實際上,它是一種不同的機制,這會在后文中講到。
該默認調度器,當協程在 [GlobalScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html) 中啟動的時候使用,它代表 [Dispatchers.Default](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html) 使用了共享的后臺線程池,所以 `GlobalScope.launch { …… }` 也可以使用相同的調度器—— `launch(Dispatchers.Default) { …… }`。
[newSingleThreadContext](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-single-thread-context.html) 為協程的運行啟動了一個線程。一個專用的線程是一種非常昂貴的資源。在真實的應用程序中兩者都必須被釋放,當不再需要的時候,使用 [close](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-executor-coroutine-dispatcher/close.html)函數,或存儲在一個頂層變量中使它在整個應用程序中被重用。
### 非受限調度器 vs 受限調度器
[Dispatchers.Unconfined](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-unconfined.html) 協程調度器在調用它的線程啟動了一個協程,但它僅僅只是運行到第一個掛起點。掛起后,它恢復線程中的協程,而這完全由被調用的掛起函數來決定。非受限的調度器非常適用于執行不消耗 CPU 時間的任務,以及不更新局限于特定線程的任何共享數據(如UI)的協程。
另一方面,該調度器默認繼承了外部的 [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html)。[runBlocking](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) 協程的默認調度器,特別是,當它被限制在了調用者線程時,繼承自它將會有效地限制協程在該線程運行并且具有可預測的 FIFO 調度。
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
launch(Dispatchers.Unconfined) { // 非受限的——將和主線程一起工作
println("Unconfined : I'm working in thread ${Thread.currentThread().name}")
delay(500)
println("Unconfined : After delay in thread ${Thread.currentThread().name}")
}
launch { // 父協程的上下文,主 runBlocking 協程
println("main runBlocking: I'm working in thread ${Thread.currentThread().name}")
delay(1000)
println("main runBlocking: After delay in thread ${Thread.currentThread().name}")
}
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-02.kt)獲取完整代碼。
執行后的輸出
```text
Unconfined : I'm working in thread main
main runBlocking: I'm working in thread main
Unconfined : After delay in thread kotlinx.coroutines.DefaultExecutor
main runBlocking: After delay in thread main
```
所以,該協程的上下文繼承自 `runBlocking {...}` 協程并在`main` 線程中運行,當 [delay](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html) 函數調用的時候,非受限的那個協程在默認的執行者線程中恢復執行。
> 非受限的調度器是一種高級機制,可以在某些極端情況下提供幫助而不需要調度協程以便稍后執行或產生不希望的副作用,因為某些操作必須立即在協程中執行。非受限調度器不應該在通常的代碼中使用。
### 調試協程與線程
協程可以在一個線程上掛起并在其它線程上恢復。
甚至一個單線程的調度器也是難以弄清楚協程在何時何地正在做什么事情。使用通常調試應用程序的方法是讓線程在每一個日志文件的日志聲明中打印線程的名字。這種特性在日志框架中是普遍受支持的。但是在使用協程時,單獨的線程名稱不會給出很多協程上下文信息,所以`kotlinx.coroutines` 包含了調試工具來讓它更簡單。
使用 `-Dkotlinx.coroutines.debug` JVM 參數運行下面的代碼:
```kotlin
import kotlinx.coroutines.*
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun main() = runBlocking<Unit> {
//sampleStart
val a = async {
log("I'm computing a piece of the answer")
6
}
val b = async {
log("I'm computing another piece of the answer")
7
}
log("The answer is ${a.await() * b.await()}")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-03.kt)獲取完整代碼。
這里有三個協程,包括 `runBlocking` 內的主協程 (#1) ,以及計算延期的值的另外兩個協程 `a` (#2) 和 `b` (#3)。它們都在 `runBlocking` 上下文中執行并且被限制在了主線程內。這段代碼的輸出如下:
```text
[main @coroutine#2] I'm computing a piece of the answer
[main @coroutine#3] I'm computing another piece of the answer
[main @coroutine#1] The answer is 42
```
這個 `log` 函數在方括號種打印了線程的名字,并且你可以看到它是 `main`線程,并且附帶了當前正在其上執行的協程的標識符。這個標識符在調試模式開啟時,將連續分配給所有創建的協程。
> 當 JVM 以 `-ea` 參數配置運行時,調試模式也會開啟。你可以在 [DEBUG_PROPERTY_NAME](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-d-e-b-u-g_-p-r-o-p-e-r-t-y_-n-a-m-e.html) 屬性的文檔中閱讀有關調試工具的更多信息。
### 在不同線程間跳轉
使用 `-Dkotlinx.coroutines.debug` JVM 參數運行下面的代碼(參見[調試](http://www.kotlincn.net/docs/reference/coroutines/coroutine-context-and-dispatchers.html#%E8%B0%83%E8%AF%95%E5%8D%8F%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B)):
```kotlin
import kotlinx.coroutines.*
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun main() {
//sampleStart
newSingleThreadContext("Ctx1").use { ctx1 ->
newSingleThreadContext("Ctx2").use { ctx2 ->
runBlocking(ctx1) {
log("Started in ctx1")
withContext(ctx2) {
log("Working in ctx2")
}
log("Back to ctx1")
}
}
}
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-04.kt)獲取完整代碼。
它演示了一些新技術。其中一個使用 [runBlocking](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) 來顯式指定了一個上下文,并且另一個使用 [withContext](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html) 函數來改變協程的上下文,而仍然駐留在相同的協程中,正如可以在下面的輸出中所見到的:
```text
[Ctx1 @coroutine#1] Started in ctx1
[Ctx2 @coroutine#1] Working in ctx2
[Ctx1 @coroutine#1] Back to ctx1
```
注意,在這個例子中,當我們不再需要某個在 [newSingleThreadContext](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-single-thread-context.html) 中創建的線程的時候,它使用了 Kotlin 標準庫中的 `use` 函數來釋放該線程。
### 上下文中的作業
協程的 [Job](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html) 是上下文的一部分,并且可以使用`coroutineContext [Job]` 表達式在上下文中檢索它:
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
println("My job is ${coroutineContext[Job]}")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-05.kt)獲取完整代碼。
在[調試模式](http://www.kotlincn.net/docs/reference/coroutines/coroutine-context-and-dispatchers.html#debugging-coroutines-and-threads)下,它將輸出如下這些信息:
```
My job is "coroutine#1":BlockingCoroutine{Active}@6d311334
```
請注意,[CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html) 中的 [isActive](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.html) 只是`coroutineContext[Job]?.isActive == true` 的一種方便的快捷方式。
### 子協程
當一個協程被其它協程在 [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html) 中啟動的時候,它將通過 [CoroutineScope.coroutineContext](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/coroutine-context.html) 來承襲上下文,并且這個新協程的 [Job](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html) 將會成為父協程作業的 _子_ 作業。當一個父協程被取消的時候,所有它的子協程也會被遞歸的取消。
然而,當使用 [GlobalScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html) 來啟動一個協程時,則新協程的作業沒有父作業。因此它與這個啟動的作用域無關且獨立運作。
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
// 啟動一個協程來處理某種傳入請求(request)
val request = launch {
// 孵化了兩個子作業, 其中一個通過 GlobalScope 啟動
GlobalScope.launch {
println("job1: I run in GlobalScope and execute independently!")
delay(1000)
println("job1: I am not affected by cancellation of the request")
}
// 另一個則承襲了父協程的上下文
launch {
delay(100)
println("job2: I am a child of the request coroutine")
delay(1000)
println("job2: I will not execute this line if my parent request is cancelled")
}
}
delay(500)
request.cancel() // 取消請求(request)的執行
delay(1000) // 延遲一秒鐘來看看發生了什么
println("main: Who has survived request cancellation?")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-06.kt)獲取完整代碼。
這段代碼的輸出如下:
```text
job1: I run in GlobalScope and execute independently!
job2: I am a child of the request coroutine
job1: I am not affected by cancellation of the request
main: Who has survived request cancellation?
```
### 父協程的職責
一個父協程總是等待所有的子協程執行結束。父協程并不顯式的跟蹤所有子協程的啟動,并且不必使用 [Job.join](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html) 在最后的時候等待它們:
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
// 啟動一個協程來處理某種傳入請求(request)
val request = launch {
repeat(3) { i -> // 啟動少量的子作業
launch {
delay((i + 1) * 200L) // 延遲 200 毫秒、400 毫秒、600 毫秒的時間
println("Coroutine $i is done")
}
}
println("request: I'm done and I don't explicitly join my children that are still active")
}
request.join() // 等待請求的完成,包括其所有子協程
println("Now processing of the request is complete")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-07.kt)獲取完整代碼。
>
結果如下所示:
```text
request: I'm done and I don't explicitly join my children that are still active
Coroutine 0 is done
Coroutine 1 is done
Coroutine 2 is done
Now processing of the request is complete
```
### 命名協程以用于調試
當協程經常打印日志并且你只需要關聯來自同一個協程的日志記錄時,則自動分配的 id 是非常好的。然而,當一個協程與特定請求的處理相關聯時或做一些特定的后臺任務,最好將其明確命名以用于調試目的。[CoroutineName](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-name/index.html) 上下文元素與線程名具有相同的目的。當[調試模式](http://www.kotlincn.net/docs/reference/coroutines/coroutine-context-and-dispatchers.html#debugging-coroutines-and-threads)開啟時,它被包含在正在執行此協程的線程名中。
下面的例子演示了這一概念:
```kotlin
import kotlinx.coroutines.*
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun main() = runBlocking(CoroutineName("main")) {
//sampleStart
log("Started main coroutine")
// 運行兩個后臺值計算
val v1 = async(CoroutineName("v1coroutine")) {
delay(500)
log("Computing v1")
252
}
val v2 = async(CoroutineName("v2coroutine")) {
delay(1000)
log("Computing v2")
6
}
log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-08.kt)獲取完整代碼。
程序執行使用了 `-Dkotlinx.coroutines.debug` JVM 參數,輸出如下所示:
```text
[main @main#1] Started main coroutine
[main @v1coroutine#2] Computing v1
[main @v2coroutine#3] Computing v2
[main @main#1] The answer for v1 / v2 = 42
```
### 組合上下文中的元素
有時我們需要在協程上下文中定義多個元素。我們可以使用 `+` 操作符來實現。比如說,我們可以顯式指定一個調度器來啟動協程并且同時顯式指定一個命名:
```kotlin
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
launch(Dispatchers.Default + CoroutineName("test")) {
println("I'm working in thread ${Thread.currentThread().name}")
}
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-09.kt)獲取完整代碼。
這段代碼使用了 `-Dkotlinx.coroutines.debug` JVM 參數,輸出如下所示:
```text
I'm working in thread DefaultDispatcher-worker-1 @test#2
```
### 協程作用域
讓我們將關于上下文,子協程以及作業的知識綜合在一起。假設我們的應用程序擁有一個具有生命周期的對象,但這個對象并不是一個協程。舉例來說,我們編寫了一個 Android 應用程序并在 Android 的 activity 上下文中啟動了一組協程來使用異步操作拉取并更新數據以及執行動畫等等。所有這些協程必須在這個 activity 銷毀的時候取消以避免內存泄漏。當然,我們也可以手動操作上下文與作業,以結合 activity 的生命周期與它的協程,但是`kotlinx.coroutines` 提供了一個封裝:[CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html) 的抽象。你應該已經熟悉了協程作用域,因為所有的協程構建器都聲明為在它之上的擴展。
我們通過創建一個 [CoroutineScope] 實例來管理協程的生命周期,并使它與activity 的生命周期相關聯。`CoroutineScope` 可以通過 [CoroutineScope()] 創建或者通過[MainScope()](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html)工廠函數。前者創建了一個通用作用域,而后者為使用 [Dispatchers.Main] 作為默認調度器的 UI 應用程序創建作用域:
```kotlin
class Activity {
private val mainScope = MainScope()
fun destroy() {
mainScope.cancel()
}
// 繼續運行……
```
或者,我們可以在這個 `Activity` 類中實現 [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html) 接口。最好的方法是使用具有默認工廠函數的委托。
我們也可以將所需的調度器與作用域合并(我們在這個示例中使用 [Dispatchers.Default](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html))。
```kotlin
class Activity : CoroutineScope by CoroutineScope(Dispatchers.Default) {
// 繼續運行……
```
現在,在這個 `Activity` 的作用域中啟動協程,且沒有明確指定它們的上下文。在示例中,我們啟動了十個協程并延遲不同的時間:
```kotlin
// 在 Activity 類中
fun doSomething() {
// 在示例中啟動了 10 個協程,且每個都工作了不同的時長
repeat(10) { i ->
launch {
delay((i + 1) * 200L) // 延遲 200 毫秒、400 毫秒、600 毫秒等等不同的時間
println("Coroutine $i is done")
}
}
}
} // Activity 類結束
```
在 main 函數中我們創建 activity,調用測試函數 `doSomething`,并且在 500 毫秒后銷毀這個 activity。這取消了從 `doSomething` 啟動的所有協程。我們可以觀察到這些是由于在銷毀之后,即使我們再等一會兒,activity 也不再打印消息。
```kotlin
import kotlin.coroutines.*
import kotlinx.coroutines.*
class Activity : CoroutineScope by CoroutineScope(Dispatchers.Default) {
fun destroy() {
cancel() // Extension on CoroutineScope
}
// 繼續運行……
// class Activity continues
fun doSomething() {
// 在示例中啟動了 10 個協程,且每個都工作了不同的時長
repeat(10) { i ->
launch {
delay((i + 1) * 200L) // 延遲 200 毫秒、400 毫秒、600 毫秒等等不同的時間
println("Coroutine $i is done")
}
}
}
} // Activity 類結束
fun main() = runBlocking<Unit> {
//sampleStart
val activity = Activity()
activity.doSomething() // 運行測試函數
println("Launched coroutines")
delay(500L) // 延遲半秒鐘
println("Destroying activity!")
activity.destroy() // 取消所有的協程
delay(1000) // 為了在視覺上確認它們沒有工作
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-10.kt)獲取完整代碼。
這個示例的輸出如下所示:
```text
Launched coroutines
Coroutine 0 is done
Coroutine 1 is done
Destroying activity!
```
你可以看到,只有前兩個協程打印了消息,而另一個協程在`Activity.destroy()` 中單次調用了 `job.cancel()`。
### 線程局部數據
有時,能夠將一些線程局部數據傳遞到協程與協程之間是很方便的。 然而,由于它們不受任何特定線程的約束,如果手動完成,可能會導致出現樣板代碼。
[`ThreadLocal`](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html),[asContextElement](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.lang.-thread-local/as-context-element.html) 擴展函數在這里會充當救兵。它創建了額外的上下文元素,且保留給定 `ThreadLocal` 的值,并在每次協程切換其上下文時恢復它。
它很容易在下面的代碼中演示:
```kotlin
import kotlinx.coroutines.*
val threadLocal = ThreadLocal<String?>() // 聲明線程局部變量
fun main() = runBlocking<Unit> {
//sampleStart
threadLocal.set("main")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) {
println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
yield()
println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
}
job.join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
//sampleEnd
}
```
> 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-context-11.kt)獲取完整代碼。
在這個例子中我們使用 [Dispatchers.Default](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html) 在后臺線程池中啟動了一個新的協程,所以它工作在線程池中的不同線程中,但它仍然具有線程局部變量的值,我們指定使用 `threadLocal.asContextElement(value = "launch")`,無論協程執行在什么線程中都是沒有問題的。因此,其輸出如([調試](http://www.kotlincn.net/docs/reference/coroutines/coroutine-context-and-dispatchers.html#%E8%B0%83%E8%AF%95%E5%8D%8F%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B))所示:
```text
Pre-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main'
Launch start, current thread: Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main], thread local value: 'launch'
After yield, current thread: Thread[DefaultDispatcher-worker-2 @coroutine#2,5,main], thread local value: 'launch'
Post-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main'
```
這很容易忘記去設置相應的上下文元素。如果運行協程的線程不同,在協程中訪問的線程局部變量則可能會產生意外的值。為了避免這種情況,建議使用 [ensurePresent](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.lang.-thread-local/ensure-present.html)方法并且在不正確的使用時快速失敗。
`ThreadLocal` 具有一流的支持,可以與任何 `kotlinx.coroutines` 提供的原語一起使用。但它有一個關鍵限制,即:當一個線程局部變量變化時,則這個新值不會傳播給協程調用者(因為上下文元素無法追蹤所有 `ThreadLocal` 對象訪問),并且下次掛起時更新的值將丟失。使用 [withContext](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html) 在協程中更新線程局部變量,詳見 [asContextElement](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.lang.-thread-local/as-context-element.html)。
另外,一個值可以存儲在一個可變的域中,例如 `class Counter(var i: Int)`,是的,反過來,可以存儲在線程局部的變量中。然而,在這個案例中你完全有責任來進行同步可能的對這個可變的域進行的并發的修改。
對于高級的使用,例如,那些在內部使用線程局部傳遞數據的用于與日志記錄 MDC 集成,以及事務上下文或任何其它庫,請參見需要實現的[ThreadContextElement](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-thread-context-element/index.html) 接口的文檔。
[Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html
[CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/index.html
[launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html
[async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html
[CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html
[Dispatchers.Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-unconfined.html
[GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html
[Dispatchers.Default]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html
[newSingleThreadContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-single-thread-context.html
[ExecutorCoroutineDispatcher.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-executor-coroutine-dispatcher/close.html
[runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html
[delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html
[DEBUG_PROPERTY_NAME]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-d-e-b-u-g_-p-r-o-p-e-r-t-y_-n-a-m-e.html
[withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html
[isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.html
[CoroutineScope.coroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/coroutine-context.html
[Job.join]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html
[CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-name/index.html
[CoroutineScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope.html
[MainScope()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html
[Dispatchers.Main]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html
[asContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.lang.-thread-local/as-context-element.html
[ensurePresent]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.lang.-thread-local/ensure-present.html
[ThreadContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-thread-context-element/index.html
- 前言
- Kotlin簡介
- IntelliJ IDEA技巧總結
- idea設置類注釋和方法注釋模板
- 像Android Studion一樣創建工程
- Gradle
- Gradle入門
- Gradle進階
- 使用Gradle創建一個Kotlin工程
- 環境搭建
- Androidstudio平臺搭建
- Eclipse的Kotlin環境配置
- 使用IntelliJ IDEA
- Kotlin學習路線
- Kotlin官方中文版文檔教程
- 概述
- kotlin用于服務器端開發
- kotlin用于Android開發
- kotlin用于JavaScript開發
- kotlin用于原生開發
- Kotlin 用于數據科學
- 協程
- 多平臺
- 新特性
- 1.1的新特性
- 1.2的新特性
- 1.3的新特性
- 開始
- 基本語法
- 習慣用法
- 編碼規范
- 基礎
- 基本類型
- 包與導入
- 控制流
- 返回與跳轉
- 類與對象
- 類與繼承
- 屬性與字段
- 接口
- 可見性修飾符
- 擴展
- 數據類
- 密封類
- 泛型
- 嵌套類
- 枚舉類
- 對象
- 類型別名
- 內嵌類
- 委托
- 委托屬性
- 函數與Lambda表達式
- 函數
- Lambda表達式
- 內聯函數
- 集合
- 集合概述
- 構造集合
- 迭代器
- 區間與數列
- 序列
- 操作概述
- 轉換
- 過濾
- 加減操作符
- 分組
- 取集合的一部分
- 取單個元素
- 排序
- 聚合操作
- 集合寫操作
- List相關操作
- Set相關操作
- Map相關操作
- 多平臺程序設計
- 平臺相關聲明
- 以Gradle創建
- 更多語言結構
- 解構聲明
- 類型檢測與轉換
- This表達式
- 相等性
- 操作符重載
- 空安全
- 異常
- 注解
- 反射
- 作用域函數
- 類型安全的構造器
- Opt-in Requirements
- 核心庫
- 標準庫
- kotlin.test
- 參考
- 關鍵字與操作符
- 語法
- 編碼風格約定
- Java互操作
- Kotlin中調用Java
- Java中調用Kotlin
- JavaScript
- 動態類型
- kotlin中調用JavaScript
- JavaScript中調用kotlin
- JavaScript模塊
- JavaScript反射
- JavaScript DCE
- 原生
- 并發
- 不可變性
- kotlin庫
- 平臺庫
- 與C語言互操作
- 與Object-C及Swift互操作
- CocoaPods集成
- Gradle插件
- 調試
- FAQ
- 協程
- 協程指南
- 基礎
- 取消與超時
- 組合掛起函數
- 協程上下文與調度器
- 異步流
- 通道
- 異常處理與監督
- 共享的可變狀態與并發
- Select表達式(實驗性)
- 工具
- 編寫kotlin代碼文檔
- 使用Kapt
- 使用Gradle
- 使用Maven
- 使用Ant
- Kotlin與OSGI
- 編譯器插件
- 編碼規范
- 演進
- kotlin語言演進
- 不同組件的穩定性
- kotlin1.3的兼容性指南
- 常見問題
- FAQ
- 與Java比較
- 與Scala比較(官方已刪除)
- Google開發者官網簡介
- Kotlin and Android
- Get Started with Kotlin on Android
- Kotlin on Android FAQ
- Android KTX
- Resources to Learn Kotlin
- Kotlin樣品
- Kotlin零基礎到進階
- 第一階段興趣入門
- kotlin簡介和學習方法
- 數據類型和類型系統
- 入門
- 分類
- val和var
- 二進制基礎
- 基礎
- 基本語法
- 包
- 示例
- 編碼規范
- 代碼注釋
- 異常
- 根類型“Any”
- Any? 可空類型
- 可空性的實現原理
- kotlin.Unit類型
- kotlin.Nothing類型
- 基本數據類型
- 數值類型
- 布爾類型
- 字符型
- 位運算符
- 變量和常量
- 語法和運算符
- 關鍵字
- 硬關鍵字
- 軟關鍵字
- 修飾符關鍵字
- 特殊標識符
- 操作符和特殊符號
- 算術運算符
- 賦值運算符
- 比較運算符
- 邏輯運算符
- this關鍵字
- super關鍵字
- 操作符重載
- 一元操作符
- 二元操作符
- 字符串
- 字符串介紹和屬性
- 字符串常見方法操作
- 字符串模板
- 數組
- 數組介紹創建及遍歷
- 數組常見方法和屬性
- 數組變化以及下標越界問題
- 原生數組類型
- 區間
- 正向區間
- 逆向區間
- 步長
- 類型檢測與類型轉換
- is、!is、as、as-運算符
- 空安全
- 可空類型變量
- 安全調用符
- 非空斷言
- Elvis操作符
- 可空性深入
- 可空性和Java
- 函數
- 函數式編程概述
- OOP和FOP
- 函數式編程基本特性
- 組合與范疇
- 在Kotlin中使用函數式編程
- 函數入門
- 函數作用域
- 函數加強
- 命名參數
- 默認參數
- 可變參數
- 表達式函數體
- 頂層、嵌套、中綴函數
- 尾遞歸函數優化
- 函數重載
- 控制流
- if表達式
- when表達式
- for循環
- while循環
- 循環中的 Break 與 continue
- return返回
- 標簽處返回
- 集合
- list集合
- list集合介紹和操作
- list常見方法和屬性
- list集合變化和下標越界
- set集合
- set集合介紹和常見操作
- set集合常見方法和屬性
- set集合變換和下標越界
- map集合
- map集合介紹和常見操作
- map集合常見方法和屬性
- map集合變換
- 集合的函數式API
- map函數
- filter函數
- “ all ”“ any ”“ count ”和“ find ”:對集合應用判斷式
- 別樣的求和方式:sumBy、sum、fold、reduce
- 根據人的性別進行分組:groupBy
- 扁平化——處理嵌套集合:flatMap、flatten
- 惰性集合操作:序列
- 區間、數組、集合之間轉換
- 面向對象
- 面向對象-封裝
- 類的創建及屬性方法訪問
- 類屬性和字段
- 構造器
- 嵌套類(內部類)
- 枚舉類
- 枚舉類遍歷&枚舉常量常用屬性
- 數據類
- 密封類
- 印章類(密封類)
- 面向對象-繼承
- 類的繼承
- 面向對象-多態
- 抽象類
- 接口
- 接口和抽象類的區別
- 面向對象-深入
- 擴展
- 擴展:為別的類添加方法、屬性
- Android中的擴展應用
- 優化Snackbar
- 用擴展函數封裝Utils
- 解決煩人的findViewById
- 擴展不是萬能的
- 調度方式對擴展函數的影響
- 被濫用的擴展函數
- 委托
- 委托類
- 委托屬性
- Kotlin5大內置委托
- Kotlin-Object關鍵字
- 單例模式
- 匿名類對象
- 伴生對象
- 作用域函數
- let函數
- run函數
- with函數
- apply函數
- also函數
- 標準庫函數
- takeIf 與 takeUnless
- 第二階段重點深入
- Lambda編程
- Lambda成員引用高階函數
- 高階函數
- 內聯函數
- 泛型
- 泛型的分類
- 泛型約束
- 子類和子類型
- 協變與逆變
- 泛型擦除與實化類型
- 泛型類型參數
- 泛型的背后:類型擦除
- Java為什么無法聲明一個泛型數組
- 向后兼容的罪
- 類型擦除的矛盾
- 使用內聯函數獲取泛型
- 打破泛型不變
- 一個支持協變的List
- 一個支持逆變的Comparator
- 協變和逆變
- 第三階段難點突破
- 注解和反射
- 聲明并應用注解
- DSL
- 協程
- 協程簡介
- 協程的基本操作
- 協程取消
- 管道
- 慕課霍丙乾協程筆記
- Kotlin與Java互操作
- 在Kotlin中調用Java
- 在Java中調用Kotlin
- Kotlin與Java中的操作對比
- 第四階段專題練習
- 朱凱Kotlin知識點總結
- Kotlin 基礎
- Kotlin 的變量、函數和類型
- Kotlin 里那些「不是那么寫的」
- Kotlin 里那些「更方便的」
- Kotlin 進階
- Kotlin 的泛型
- Kotlin 的高階函數、匿名函數和 Lambda 表達式
- Kotlin協程
- 初識
- 進階
- 深入
- Kotlin 擴展
- 會寫「18.dp」只是個入門——Kotlin 的擴展函數和擴展屬性(Extension Functions / Properties)
- Kotlin實戰-開發Android