常用的一些:
GlobalScope.launch{}
: 一般用于测试delay()
: 类似于Thread.sleep(),但是delay()不会阻塞线程runBlocking{}
: 阻塞当前线程,直到协程结束.coroutineScope{}
: 不阻塞当前线程,直到这个作用域下的协程都执行完,才往下执行.withTimeout(1300L) {}
: 超时取消协程CoroutineScope
fun main() {
runBlocking { // this: CoroutineScope
test1()
}
runBlocking {
test2()
}
}
private suspend fun test2() {
withTimeout(1300L) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
}
// test for coroutineScope
private suspend fun test1() {
coroutineScope {
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // 创建一个协程作用域
launch {
delay(500L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // 这一行会在内嵌 launch 之前输出
}
println ("Coroutine scope is over")
}
println ("Coroutine2 scope is over")
}