<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                **目錄** [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
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看