Kotlin协程

协程(使用gradle构建demo)

  • 需要导入的包以及中央库

    dependencies {
        ...
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    }
    repositories {
        jcenter()
    }
    
  1. 启动协程的几个方法

    1. launch

      GlobalScope.launch {
          delay(1000)
          println("Hello")
      }
      
    2. runBlocking {}

      runBlocking {
          ...
      }
      
    3. async/await(返回一个Defferred<T>实例)

      //依次返回1到一百万的的数
      val deferred = (1..1_000_000).map { n ->
          GlobalScope.async {
              n
          }
      }
      //挂起函数只被允许在协程或另一个挂起函数中调用,所以讲await()放入runBlocking中挂起,这是异步并行操作
      runBlocking {
          val sum = deferred.sumBy { it.await() }
          println("Sum: $sum")
      }
      
  1. 协程的结束cancel()

    fun main(args: Array<String>) = runBlocking { //使用runBlock来进行外部线程和内部协程的切换
        val launch = launch {
            var count: Int = 0
            while (true) {
                count++
                println(count)
                delay(500)
            }
        }
        delay(5000)
        println("准备终止该协程函数")
        launch.cancel()
        println("结束终止该协程函数")
    }
    
  1. 关键词suspend

    • 因为协程函数只能够协程或者另一个挂起函数中使用,所以如果在普通的函数中使用了协程函数,则需要将普通函数添加suspend修饰。

      suspend fun workload(n: Int): Int {
          delay(1000)
          return n
      }
      GlobalScope.async {
          workload(n)
      }
      //or 主函数在调用的时候也必须声明为suspend
      suspend fun main(args: Array<String>) {
      
          print(workload(5))
      
      }
      
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 轻量级线程:协程 在常用的并发模型中,多进程、多线程、分布式是最普遍的,不过近些年来逐渐有一些语言以first-c...
    Tenderness4阅读 6,417评论 2 10
  • 前言  今年的Google开发者大会已表明将Kotlin作为其正式的语言,现Google大力主推Kotlin, 在...
    Vgecanshang阅读 3,571评论 0 15
  • 你的第一个协程 输出结果 从本质上讲,协同程序是轻量级的线程。它们是与发布 协同程序构建器一起启动的。您可以实现相...
    十方天仪君阅读 2,573评论 0 2
  • 初遇Kotlin协程(coroutine) 这篇文章我们将建立协程项目,并用Coroutines编写相关代码。 K...
    xiongmao_123阅读 266评论 0 0