kotin 学习笔记: 协程coroutine 和JVM thread 对比

13 阅读1分钟

协程(coroutine) 是可以挂起的,像线程thread一样,并行执行,但是二者有很大的区别。最大的区别是对内存的需求,一个线程,需要2M左右的内存开销,但是一个协程不会绑定一个线程,协程挂起的时候,不会阻塞当前线程,仍然可以执行其他线程,比线程更轻量,消耗的内存更小,一个进程可以执行百万个协程而不会让系统的资源消耗殆尽。我们试试50000个协程和50000个线程,没间隔5秒打印(.)来进行对比。 分别执行 printPeriods() 和 threadTest() ,明显可以感觉到 printPeriods()更快。 按照一个thread需要2m内存,50000个需要100G 内存,一般会报 OOM错误,跟电脑配置,jdk版本 有关,我的电脑64G内存,JAVA -17, 居然没有报OOM ,但是执行速度还是有明显的差异。

suspend fun main(){
    printPeriods()
}
suspend fun printPeriods()= coroutineScope {
    repeat(50_000){
        launch{
            delay(5.seconds)
            print(".")
        }
    }
}
fun threadTest(){
    repeat(50_000){
        thread {
            Thread.sleep(5000L)
            print(".")
        }
    }
}

参考官网 kotlinlang.org/docs/corout…