kotlin协程coroutineScope

2023-05-16

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-

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

kotlin协程coroutineScope 的相关文章

随机推荐