funmain() = runBlocking { val job1 = GlobalScope.launch { log("launch before delay") delay(100) log("launch after delay") } val job2 = GlobalScope.launch { log("launch2 before delay") delay(200) log("launch2 after delay") }
[DefaultDispatcher-worker-2 @coroutine#3] launch2 before delay [DefaultDispatcher-worker-1 @coroutine#2] launch before delay [DefaultDispatcher-worker-1 @coroutine#2] launch after delay [DefaultDispatcher-worker-1 @coroutine#3] launch2 after delay
这个输出有两个要点:
从线程名推断,两个协程很可能运行在某个线程池中
第二个协程先运行在 worker-2,然后又运行在 worker-1
关于第一点, launch 的文档有这么一句话:
If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used.
funmain() = runBlocking { val dispatcher = DummyDispatcher() log("which thread am I in?") val job = GlobalScope.launch(dispatcher) { log("launch before delay") delay(100) log("launch after delay") }
job.join() }
由于我们的 DummyDispatcher 什么也没做,协程会继续在原来的线程中执行。运行结果为:
1 2 3
[main @coroutine#1] which thread am I in? [main @coroutine#1] launch before delay [kotlinx.coroutines.DefaultExecutor] launch after delay
funmain() = runBlocking { val dispatcher = SingleThreadedDispatcher() log("which thread am I in?") val job = GlobalScope.launch(dispatcher) { log("launch before delay") delay(100) log("launch after delay") }
job.join() dispatcher.close() }
程序的输出为:
1 2 3
[main @coroutine#1] which thread am I in? [SingleThreadedDispatcher] launch before delay [SingleThreadedDispatcher] launch after delay