Kotlin/协程基础

维基教科书,自由的教学读本

第一个协程[编辑]

运行以下程式

import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch { // 背景開啟新協程
        delay(1000L) // 不中斷其他程序的 delay 一秒,注意 delay 函式的預設單位是毫秒
        println("World!") // 在一秒後印出
    }
    println("Hello,") // 主線程在協程 delay 時繼續運作,並印出「Hello,」
    Thread.sleep(2000L) // 阻斷主線程兩秒,以維持 JVM 運作
}

会印出

Hello,
World!

Bridging blocking and non-blocking worlds[编辑]

等待开工[编辑]

Delaying for a time while another coroutine is working is not a good approach. Let's explicitly wait (in a non-blocking way) until the background Job that we have launched is complete:

val job = GlobalScope.launch { // 開啟新協程並記錄在 job 常數上
    delay(1000L)
    println("World!")
}
println("Hello,")
job.join() // 等待子協程結束

Now the result is still the same, but the code of the main coroutine is not tied to the duration of the background job in any way. Much better.

结构化的并发[编辑]

Scope builder[编辑]

Extract function refactoring[编辑]

协程是轻量的[编辑]

和线程相比,协程是非常轻量的。如果我们尝试运行以下程式

import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(100_000) { // 打開很多協程
        launch {
            delay(1000L)
            print(".")
        }
    }
}

我们开启了十万个协程,每秒之后,每个协程都印出一个点。

如果我们改用线程做一样的事,会怎样呢?正常情况下你的电脑应该会跳出内存不够的错误。

所以我们可以知道,协程是比起线程更轻量的。

全域协程有点像是守护行程[编辑]

参考资料[编辑]

https://kotlinlang.org/docs/reference/coroutines/basics.html