GlobalScope.launch { println("Unconfined: I'm working in thread ${Thread.currentThread().name}") withContext(Dispatchers.Main) { // Nested unconfined println("Main: I'm working in thread ${Thread.currentThread().name}") } println("Unconfined: I'm working in thread ${Thread.currentThread().name}") withContext(Dispatchers.IO) { // Nested unconfined println("IO: I'm working in thread ${Thread.currentThread().name}") } println("Unconfined: I'm working in thread ${Thread.currentThread().name}") }
输出:
Unconfined: I'm working in thread DefaultDispatcher-worker-1 Main: I'm working in thread main Unconfined: I'm working in thread main IO: I'm working in thread DefaultDispatcher-worker-1 Unconfined: I'm working in thread DefaultDispatcher-worker-1
使用了Dispatchers.Unconfined
GlobalScope.launch(Dispatchers.Unconfined) { println("Unconfined: I'm working in thread ${Thread.currentThread().name}") withContext(Dispatchers.Main) { // Nested unconfined println("Main: I'm working in thread ${Thread.currentThread().name}") } println("Unconfined: I'm working in thread ${Thread.currentThread().name}") withContext(Dispatchers.IO) { // Nested unconfined println("IO: I'm working in thread ${Thread.currentThread().name}") } println("Unconfined: I'm working in thread ${Thread.currentThread().name}") }
输出:
Unconfined: I'm working in thread main Main: I'm working in thread main Unconfined: I'm working in thread main IO: I'm working in thread DefaultDispatcher-worker-2 Unconfined: I'm working in thread DefaultDispatcher-worker-2