kotlin协程coroutineScope

kotlin协程coroutineScope

coroutineScope 创建独立协程作用域,直到所有启动的协程都完成后才结束自己。runBlocking 和 coroutineScope 很像,它们都需要等待内部所有相同作用域的协程结束后才会结束自己。两者主要区别是: runBlocking 阻塞当前线程,而 coroutineScope不会,coroutineScope会挂起并释放底层线程供其它协程使用。

例如:

import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.time.LocalTime

fun main() {
    println("start-")

    runBlocking {
        launch {
            delay(1000)
            println("${LocalTime.now()} - A")
        }

        coroutineScope {
            launch {
                delay(1000)
                println("${LocalTime.now()} - coroutineScope - 1")
            }

            launch {
                delay(100)
                println("${LocalTime.now()} - coroutineScope - 2")
            }
        }

        launch {
            delay(2000)
            println("${LocalTime.now()} - B")
        }
    }

    println("end-")
}

输出:

start-
17:03:09.391491300 - coroutineScope - 2
17:03:10.280958800 - A
17:03:10.280958800 - coroutineScope - 1
17:03:12.289983800 - B
end-

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/129265638