对于同一个协程作用域,协程会在那个线程运行呢?
试验代码如下:
import kotlinx.coroutines.*
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import kotlin.coroutines.resume
import kotlin.system.measureTimeMillis
@ExperimentalCoroutinesApi
fun main() = runBlocking {
val myScope = CoroutineScope(Dispatchers.Default)
myScope.launch {
doSomethingUsefulOne()
doSomethingUsefulTwo()
}
myScope.launch {
doSomethingUsefulOne()
doSomethingUsefulTwo()
}
delay(1300L)
println("main: I'm tired of waiting!")
println("main: Now I can quit.")
}
private suspend fun fileReadTest() {
val dir = System.getProperty("user.dir")
val file = File(dir, "test_file.zip")
println("path = ${file.absolutePath}")
val fileInputStream = FileInputStream(file)
val buffer = ByteArray(1024)
var bos = BufferedInputStream(fileInputStream)
var length = -1
val time = measureTimeMillis {
while (true) {
length = bos.read(buffer)
if (length <= 0) {
break
}
println("readed size = $length")
}
}
println("读取结束, 消耗时间 = $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
println("threadone = ${Thread.currentThread()}")
// delay(1000L)
cpuExecuteTime(2)
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
println("threadTwo = ${Thread.currentThread()}")
// delay(1000L)
cpuExecuteTime(2)
return 29
}
运行打出日志如下:
threadone = Thread[DefaultDispatcher-worker-1,5,main]
cup execute i = 0 second
threadone = Thread[DefaultDispatcher-worker-2,5,main]
cup execute i = 0 second
cup execute i = 1 second
threadTwo = Thread[DefaultDispatcher-worker-1,5,main]
cup execute i = 0 second
cup execute i = 1 second
threadTwo = Thread[DefaultDispatcher-worker-2,5,main]
cup execute i = 0 second
main: I'm tired of waiting!
main: Now I can quit.
从日志可以看出,对于同一次的launch, 不同的suspend方法都运行在同一个线程
对于不同的launch(协程构建器),不能保证运行在同一个线程,这与协程作用域有关系。