fun getBannerData() {
viewModelScope.launch(IO) {
Log.i("zc_test", "11111 current thread is ${Thread.currentThread()}")
withContext(Main) {
Log.i("zc_test", "22222 current thread is ${Thread.currentThread()}")
}
Log.i("zc_test", "33333 current thread is ${Thread.currentThread()}")
}
}
2019-12-19 15:40:51.786 14920-15029/com.chendroid.learning I/zc_test: 11111 current thread is Thread[DefaultDispatcher-worker-3,5,main]
2019-12-19 15:40:51.786 14920-14920/com.chendroid.learning I/zc_test: 22222 current thread is Thread[main,5,main]
2019-12-19 15:40:51.789 14920-15029/com.chendroid.learning I/zc_test: 33333 current thread is Thread[DefaultDispatcher-worker-3,5,main]
launch
suspend
测试:
fun test {
viewModelScope.launch {
println("viewModelScope.launch ${Thread.currentThread()}")
mainTest()
println("viewModelScope.launch 结束了 ${Thread.currentThread()}")
}
test2()
}
...
// mainTest() 方法
suspend fun mainTest() {
println("mainTest() start start start " + Thread.currentThread())
a()
b()
c()
println("mainTest() end end end" + Thread.currentThread())
}
// 普通函数 test2()
fun test2() {
println("test2() doing doing doing " + Thread.currentThread())
}
//普通函数 a()
fun a() {
println("a() doing doing doing " + Thread.currentThread())
}
//普通函数 c()
fun c() {
println("c() doing doing doing " + Thread.currentThread())
}
// 挂起函数 b()
suspend fun b() {
println("b() start start start" + Thread.currentThread())
coroutineScope {
println("11111 线程 是" + Thread.currentThread())
launch(IO) {
println("22222 线程 是" + Thread.currentThread())
delay(1000)
println("22222 线程结束" + Thread.currentThread())
}
println("33333 线程 是" + Thread.currentThread())
}
println("b() end end end" + Thread.currentThread())
}
I/System.out: viewModelScope.launch Thread[main,5,main]
I/System.out: mainTest() start start start Thread[main,5,main]
a() doing doing doing Thread[main,5,main]
b() start start startThread[main,5,main]
I/System.out: 11111 线程 是Thread[main,5,main]
I/System.out: 33333 线程 是Thread[main,5,main]
I/System.out: 22222 线程 是Thread[DefaultDispatcher-worker-2,5,main] 「标注 1」
I/System.out: test2() doing doing doing Thread[main,5,main] 「标注 2」
I/System.out: 22222 线程结束Thread[DefaultDispatcher-worker-9,5,main]
I/System.out: b() end end endThread[main,5,main]
c() doing doing doing Thread[main,5,main]
mainTest() end end endThread[main,5,main]
viewModelScope.launch 结束了 Thread[main,5,main]