kotlin:协程究竟运行在那个线程?

对于同一个协程作用域,协程会在那个线程运行呢?
试验代码如下:

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(协程构建器),不能保证运行在同一个线程,这与协程作用域有关系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值