美文网首页
kotlin协程 - coroutines

kotlin协程 - coroutines

作者: bf027edd3b22 | 来源:发表于2018-04-19 23:13 被阅读33次

参考文档:https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
github地址:https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#android
kotlin Android Extensions使用:https://github.com/wangjiegulu/kotlin-for-android-developers-zh/blob/master/zen_yaoqu_shi_yong_kotlinandroid_extensions.md

使用

添加依赖

dependencies{
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.21"
}

repositories{
    jcenter()
}

注:coroutines最新版本查看地址 https://github.com/Kotlin/kotlinx.coroutines/releases


什么是协程?

可以认为协程是一个轻量级的线程。和线程类似,协程也可以并行运行、相互等待、交互。协程的开销是很小的,几乎可以忽略。
我们可以创建上千个协程,只需要很小的性能;但是如果创建的是几千个线程,对于机器来说将是比较大的挑战。

如何创建和使用协程?

创建一个协程:

    launch{
        ...
    }

协程是运行在共享线程池里面的,线程会一直存在如果协程在运行的话,但是一个线程可以运行很多协程,所以就可以减少线程的创建。

ex:

    fun main(args: Array<String>){
        println("start")

        launch{
            delay(1000)
            println("hello")
        }

        Thread.sleep(2000)
        println("stop")
    }

    //out:  start
    //      hello
    //      stop

delay:只暂停协程自身,不会阻塞线程。线程会在等待期间回到线程池,执行完成后,再从线程池中恢复一个空闲的线程。

主线程会等待协程完成。

协程的开销真的很小吗?

验证:疯狂的创建一百万个线程和协程

协程是如何处理返回值的?

使用async创建一个协程,作用和launch类似,但是它会返回一个 Deferred<T>的实例,

相关文章

网友评论

      本文标题:kotlin协程 - coroutines

      本文链接:https://www.haomeiwen.com/subject/hhwgkftx.html