Kotlin Coroutines 笔记 (一)

Kotlin Coroutines 笔记 (一)_第1张图片


一. 协程

Kotlin 在1.1版本之后引入了协程的概念,目前它还是一个试验的API。

在操作系统中,我们知道进程和线程的概念以及区别。而协程相比于线程更加轻量级,协程又称微线程。

协程是一种用户态的轻量级线程,协程的调度完全由用户控制。协程拥有自己的寄存器上下文和栈。协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈,直接操作栈则基本没有内核切换的开销,可以不加锁的访问全局变量,所以上下文的切换非常快。

Kotlin 的协程是无阻塞的异步编程方式。Kotlin 允许我们使用协程来代替复杂的线程阻塞操作,并且复用原本的线程资源。

Kotlin 的协程是依靠编译器实现的, 并不需要操作系统和硬件的支持。编译器为了让开发者编写代码更简单方便, 提供了一些关键字(例如 suspend), 并在内部自动生成了一些支持型的代码。

先举两个例子来说明协程的轻量级,分别创建10w个协程和10w个线程进行测试。


  1. import kotlinx.coroutines.experimental.CommonPool

  2. import kotlinx.coroutines.experimental.delay

  3. import kotlinx.coroutines.experimental.launch

  4. import kotlinx.coroutines.experimental.runBlocking

  5. /**

  6. * Created by tony on 2018/7/18.

  7. */

  8. fun main(args: Array<String>) {

  9.    val start = System.currentTimeMillis()

  10.    runBlocking {

  11.        val jobs = List(100000) {

  12.            // 创建新的coroutine

  13.            launch(CommonPool) {

  14.                // 挂起当前上下文而非阻塞1000ms

  15.                delay(1000)

  16.                println("thread name="+Thread.currentThread().name)

  17.            }

  18.        }

  19.        jobs.forEach {

  20.            it.join()

  21.        }

  22.    }

  23.    val spend = (System.currentTimeMillis()-start)/1000

  24.    println("Coroutines: spend= $spend s")

  25. }

10w个协程的创建在本机大约花费 1 秒,经过测试100w个协程的创建大约花费11 秒。

Kotlin Coroutines 笔记 (一)_第2张图片


  1. import kotlin.concurrent.thread

  2. /**

  3. * Created by tony on 2018/7/18.

  4. */

  5. fun main(args: Array<String>) {

  6.    val start = System.currentTimeMillis()

  7.    val threads = List(100000) {

  8.        // 创建新的线程

  9.        thread {

  10.            Thread.sleep(1000)

  11.            println(Thread.currentThread().name)

  12.        }

  13.    }

  14.    threads.forEach { it.join() }

  15.    val spend = (System.currentTimeMillis()-start)/1000

  16.    println("Threads: spend= $spend s")

  17. }

Kotlin Coroutines 笔记 (一)_第3张图片

10w个线程的创建出现了OutOfMemoryError。

二. 协程常用的基本概念

2.1 CoroutineContext

协程上下文,它包含了一个默认的协程调度器。所有协程都必须在 CoroutineContext 中执行。

2.2 CoroutineDispatcher

协程调度器,它用来调度和处理任务,决定了相关协程应该在哪个或哪些线程中执行。Kotlin 的协程包含了多种协程调度器。

2.3 Continuation

按照字面意思是继续、持续的意思。协程的执行可能是分段执行的:先执行一段,挂起,再执行一段,再挂起......

Continuation 则表示每一段执行的代码,Continuation 是一个接口。

2.4 Job

任务执行的过程被封装成 Job,交给协程调度器处理。Job 是一种具有简单生命周期的可取消任务。Job 拥有三种状态:isActive、isCompleted、isCancelled。

Kotlin Coroutines 笔记 (一)_第4张图片

2.5 Deferred

Deferred 是 Job 的子类。Job 完成时是没有返回值的,Deferred 可以为任务完成时提供返回值,并且Deferred 新增了一个状态 isCompletedExceptionally。

Kotlin Coroutines 笔记 (一)_第5张图片

2.6 suspend 关键字

协程计算可以被挂起而无需阻塞线程。我们使用 suspend 关键字来修饰可以被挂起的函数。被标记为 suspend 的函数只能运行在协程或者其他 suspend 函数中。

suspend 可以修饰普通函数、扩展函数和 lambda 表达式。

三. 协程的多种使用方式

Kotlin 的协程支持多种异步模型:

Kotlin Coroutines 笔记 (一)_第6张图片

这些异步机制在 Kotlin 的协程中都有实现。

Kotlin 官方对协程提供的三种级别的能力支持, 分别是: 最底层的语言层, 中间层标准库(kotlin-stdlib), 以及最上层应用层(kotlinx.coroutines)。

3.1 协程的hello world版本

使用 launch 和 async 都能启动一个新的协程。


  1.    val job = launch {

  2.        delay(1000)

  3.        println("Hello World!")

  4.    }

  5.    Thread.sleep(2000)

或者


  1.    val deferred  = async {

  2.        delay(1000)

  3.        println("Hello World!")

  4.    }

  5.    Thread.sleep(2000)

它们分别会返回一个 Job 对象和一个 Deferred 对象。

下面使用 runBlocking 来创建协程。


  1. fun main(args: Array<String>) = runBlocking<Unit> {

  2.    launch {

  3.        delay(1000)

  4.        println("Hello World!")

  5.    }

  6.    delay(2000)

  7. }

runBlocking 创建的协程直接运行在当前线程上,同时阻塞当前线程直到结束。

launch 和 async 在创建时可以使用不同的CoroutineDispatcher,例如:CommonPool。

在 runBlocking 内还可以创建其他协程,例如launch。反之则不行。

总结:

Kotlin 的协程能够简化异步编程的代码,使用同步的方式实现异步。协程的概念和理论比较多,第一篇只是一个开始,只整理了其中一些基本概念。

文末福利:《RxJava 2.x 实战》第二次印刷送书啦

关注【Java与Android技术栈】

更多精彩内容请关注扫码

Kotlin Coroutines 笔记 (一)_第7张图片


你可能感兴趣的:(Kotlin Coroutines 笔记 (一))