import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
launch { // 使用父协程的上下文, 也就是 main 函数中的 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) { // 会被派发到 DefaultDispatcher
println("Default : I'm working in thread ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("MyOwnThread")) { // 将会在独自的新线程内执行
println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
}
//sampleEnd
}
这个示例程序的输出如下 (顺序可能略有不同):
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
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 { // 使用父协程的上下文, 也就是 main 函数中的 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
}
上面的示例程序的输出如下:
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
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
}
上面的例子中会出现 3 个协程. runBlocking 之内的主协程 (#1), 以及另外 2 个计算延迟值的协程 a (#2) 和 b (#3). 这些协程都在 runBlocking 的上下文内运行, 并且都被限定在主线程中. 这个示例程序的输出是:
[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 线程, 而且线程名称之后还加上了目前正在执行的协程 id. 当打开调试模式时, 会将所有创建的协程 id 设置为连续的数字顺序.
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
// 启动一个协程, 处理某种请求
val request = launch {
// 它启动 2 个其他的任务
launch(Job()) {
println("job1: I run in my own Job 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() // 取消对请求的处理
println("main: Who has survived request cancellation?")
delay(1000) // 将主线程延迟 1 秒, 看看结果如何
//sampleEnd
}
这个示例程序的运行结果是:
job1: I run in my own Job and execute independently!
job2: I am a child of the request coroutine
main: Who has survived request cancellation?
job1: I am not affected by cancellation of the request
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
//sampleStart
// 启动一个协程, 处理某种请求
val request = launch {
repeat(3) { i -> // 启动几个子协程
launch {
delay((i + 1) * 200L) // 各个子协程分别等待 200ms, 400ms, 600ms
println("Coroutine $i is done")
}
}
println("request: I'm done and I don't explicitly join my children that are still active")
}
request.join() // 等待 request 协程执行完毕, 包括它的所有子协程
println("Now processing of the request is complete")
//sampleEnd
}
这个示例程序的运行结果如下:
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
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'