Kotlin中协程的创建过程详析
作者:ZzT 发布时间:2023-11-27 07:45:16
为什么需要协程?
协程可以简化异步编程,可以顺序地表达程序,协程也提供了一种避免阻塞线程并用更廉价、更可控的操作替代线程阻塞的方法 – 挂起函数。
Kotlin 的协程是依靠编译器实现的, 并不需要操作系统和硬件的支持。编译器为了让开发者编写代码更简单方便, 提供了一些关键字(例如suspend), 并在内部自动生成了一些支持型的代码。
创建并启动协程
fun create.main() {
//1. 创建协程体
val coroutine = suspend {
println("in coroutine")
5
}.createCoroutine(object: Continuation<Int> {
override fun resumeWith(result: Result<Int>) {
println("coroutine end: $result")
}
override val context: CoroutineContext
get() = EmptyCoroutineContext
})
//2. 执行协程
coroutine.resume(Unit)
}
上面代码的输出结果:
in coroutine
coroutine end: Success(5)
协程的执行过程
调用栈流程如下
我们通过 suspend block#createCoroutine 得到的 coroutine 实际是 SafeContinuation 对象
SafeContinuation 实际上是代理类,其中的 delegate 属性才是真正的 Continuation 对象
suspend block 中的代码在 BaseContinuationImpl 中执行
我们的匿名内部类对象 Continuation 被回调
suspend block 是如何变为协程体被执行的?
我们分析调用栈得知,resumeWith 最终是在 BaseContinuationImpl 中执行的,下面来看看代码
@SinceKotlin("1.3")
internal abstract class BaseContinuationImpl(
public val completion: Continuation<Any?>?
) : Continuation<Any?>, CoroutineStackFrame, Serializable {
public final override fun resumeWith(result: Result<Any?>) {
var current = this
var param = result
while (true) {
probeCoroutineResumed(current)
with(current) {
val completion = completion!!
val outcome: Result<Any?> =
try {
val outcome = invokeSuspend(param) //1.这里执行了 suspend block
if (outcome === COROUTINE_SUSPENDED) return
Result.success(outcome)
} catch (exception: Throwable) {
Result.failure(exception)
}
releaseIntercepted()
if (completion is BaseContinuationImpl) {
current = completion
param = outcome
} else {
completion.resumeWith(outcome) //2.这里回调了我们的匿名内部类
return
}
}
}
}
protected abstract fun invokeSuspend(result: Result<Any?>): Any? //3. 抽象方法
}
在代码注释 1. 处,调用 current.invokeSuspend,执行了我们定义的协程体,证明 suspend block 其实是 BaseContinuationImpl 的子类
在 2. 处,协程体执行完毕后,我们的代码收到了完成回调
在 3. 处,可以发现 invokeSuspend 是个抽象方法,suspend block 就是这个方法的具体实现
下面我通过断点,进一步分析 suspend block 是通过哪个子类执行的。
可以看到 current 是名为 {文件}${方法}${变量}$1 格式的对象,证明 kotlin 编译器遇到 suspend 关键字后会帮我们生成一个 BaseContinuationImpl 的子类
那么,这个子类到底是什么呢?将 kt 编译为 .class 再通过 jadx 打开后,得到的 java 代码如下
public final class CreateCoroutineKt {
public static final void create.main() {
Continuation coroutine = ContinuationKt.createCoroutine(new CreateCoroutineKt$create.main$coroutine$1(null), new CreateCoroutineKt$create.main$coroutine$2());
Unit unit = Unit.INSTANCE;
Result.Companion companion = Result.Companion;
coroutine.resumeWith(Result.constructor-impl(unit));
}
}
final class CreateCoroutineKt$create.main$coroutine$1 extends SuspendLambda implements Function1<Continuation<? super Integer>, Object> {
int label;
CreateCoroutineKt$create.main$coroutine$1(Continuation<? super CreateCoroutineKt$create.main$coroutine$1> continuation) {
super(1, continuation);
}
@NotNull
public final Continuation<Unit> create(@NotNull Continuation<?> continuation) {
return new CreateCoroutineKt$create.main$coroutine$1(continuation);
}
@Nullable
public final Object invoke(@Nullable Continuation<? super Integer> continuation) {
return create(continuation).invokeSuspend(Unit.INSTANCE);
}
@Nullable
public final Object invokeSuspend(@NotNull Object obj) {
IntrinsicsKt.getCOROUTINE_SUSPENDED();
switch (this.label) {
case 0:
ResultKt.throwOnFailure(obj);
System.out.println((Object) "in coroutine"); //协程体的逻辑
return Boxing.boxInt(5);
default:
throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
}
}
}
明显看出,kt 编译器帮助我们把 suspend 关键字变为了 SuspendLambda 的 子类,并重写了 invokeSuspend 方法,不难猜出 SuspendLambda 继承自 BaseContinuationImp
来源:https://androidzzt.github.io/2022/01/23/kt-coroutine-create/


猜你喜欢
- TBS视频播放 TBS视频播放器可以支持市面上几乎所有的视频格式,包括mp4, flv, avi, 3gp, webm, ts,
- Vector(向量)是 java.util 包中的一个类,该类实现了类似动态数组的功能。向量和数组相似,都可以保存一组数据(数据列表)。但是
- 昨天看了一段android配置aspectj实现AOP的直播视频,就试着自己配置了一下,可能是因为我自己的AndroidStudio环境的问
- 圆形识别方案识别流程判断是否为封闭图形;根据圆的方程,取输入点集中的1/6、3/6、5/6处的三个点,求得圆的方程,获取圆心及半径;取点集中
- 在微信公众号里面需要上传头像,时间比较紧,调用学习jssdk并使用 来不及 就用了input1、使用input:file标签, 去调用系统默
- 使用正则表达式进行替换:代码片段:String documentTxt = EntityUtils.toString(entity,&quo
- 其中包含两个jsp文件,分别为login.jsp和index.jsp代码如下:login.jsp<%@ page language=&
- 文章来源:csdn 作者:chensheng913对于Java语言,最体贴的一项设计就是它并没有打算让人们为了写程序而写程序——人们也需要考
- 在写程序的时候,有时候可能需要设置小数的位数,那么java中有哪几种保留小数位数的方法呢?本文以两位小数为例给出四种方法。package C
- 本文实例为大家分享了C++实现哈夫曼编码的具体代码,供大家参考,具体内容如下#include<iostream>#include
- 本文实例讲述了java之swing表格实现方法。分享给大家供大家参考。具体如下:import java.awt.*;import java.
- 第 1 步:将这个 Spring Boot 项目的打包方式设置为 war。<packaging>war</packagin
- 前言在实际开发中,大多数情况下都需要对 SQL 传入参数以获得想要的结果集,传入的情况分为两种情况:1、SQL语句的拼接,比如表名、like
- /* * 获取当前的手机号 &nb
- TV 3D卡片无限循环效果,供大家参考,具体内容如下##前言1、需求:实现3个卡片实现无限循环效果:1-2-3-1-2-3-1…,而且要实现
- 本文实例展示了C#中this指针的用法,对于初学者进一步牢固掌握C#有很大帮助,具体内容如下:一、this指针是什么:这里有一些面向对象编程
- 样式如下所示:布局:layoutdialog_set_pwd.xml<?xml version="." encod
- File 类:文件和目录路径名的抽象表示。注意:File 类只能操作文件的属性,文件的内容是不能操作的。1、File 类的字段我们知道,各个
- 本文实例为大家分享了Handler实现倒计时功能的具体代码,供大家参考,具体内容如下1、需求1.1 实现目标当后台传递一个时间戳时,与当前系
- 1、CS、BS架构定义CS(Client/Server):客户端----服务器结构。C/S结构在技术上很成熟,它的主要特点是交互性强、具有安