newSingleThreadContext("Ctx1").use { ctx1 ->
newSingleThreadContext("Ctx2").use { ctx2 ->
runBlocking(ctx1) {
log("Started in ctx1")
withContext(ctx2) {
log("Working in ctx2")
}
log("Back to ctx1")
}
}
}
launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread
println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
}
https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#jumping-between-threads
导入协程
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10'
全局协程测试
coroutineIoScope.launch {
Timber.e("coroutineIoScope thread id = " + Thread.currentThread().id)
}
coroutineDbScope.launch {
Timber.e("coroutineDbScope thread id = " + Thread.currentThread().id)
}
coroutineFileScope.launch {
Timber.e("coroutineFileScope thread id = " + Thread.currentThread().id)
}
coroutineMainScope.launch {
Timber.e("coroutineMainScope thread id = " + Thread.currentThread().id)
}
Timber.e("Main thread id = " + Thread.currentThread().id)
协程文件
@file:OptIn(DelicateCoroutinesApi::class)
package com.mgg.core.coroutine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.newSingleThreadContext
// https://www.jianshu.com/p/76d2f47b900d
val singleIOThreadContext = newSingleThreadContext("CoroutineIoScope")
val singleDBThreadContext = newSingleThreadContext("CoroutineDbScope")
val singleFileThreadContext = newSingleThreadContext("CoroutineFileScope")
val coroutineIoScope = CoroutineScope(singleIOThreadContext)
val coroutineDbScope = CoroutineScope(singleDBThreadContext)
val coroutineFileScope = CoroutineScope(singleFileThreadContext)
val coroutineMainScope = MainScope()
网友评论