完整调用流程图
📱 用户调用 launch { ... }
↓
🏗️ CoroutineScope.launch() → 创建协程入口
↓
🔧 newCoroutineContext() → 组合协程上下文
↓
🏭 StandaloneCoroutine() → 创建协程实例
↓
🚀 coroutine.start() → 启动协程
↓
📋 CoroutineStart.DEFAULT.invoke() → 选择启动策略
↓
🔒 startCoroutineCancellable() → 可取消启动
↓
🛡️ runSafely { ... } → 异常安全包装
├── 🏭 createCoroutineUnintercepted() → 创建原始状态机
│ ↓
│ 📝 编译器生成状态机.create() → 实例化状态机
│ ↓
│ 🔗 .intercepted() → 添加调度器拦截
│ ↓
│ 📦 DispatchedContinuation包装 → 线程调度包装
│ ↓
│ ▶️ .resumeCancellableWith() → 开始执行
│
└── ❌ 异常处理 → completion.resumeWith(failure)
↓
🎯 DispatchedContinuation.resumeCancellableWith()
↓
❓ 是否需要线程调度?
├── ✅ 需要调度 → dispatcher.dispatch() → 线程切换
│ ↓
│ 🧵 目标线程执行 DispatchedTask.run()
│
└── ❌ 直接执行 → executeUnconfined()
↓
🔄 BaseContinuationImpl.resumeWith() → 状态机核心循环
↓
⚙️ 状态机.invokeSuspend() → 执行用户代码
↓
❓ 执行结果判断
├── ⏸️ 遇到挂起点 → 返回 COROUTINE_SUSPENDED
│ ↓
│ ⏳ 等待异步操作完成
│ ↓
│ 📞 异步回调 continuation.resumeWith() → 恢复执行
│ ↓
│ 🔄 继续状态机循环
│
└── ✅ 正常完成 → 返回结果值
↓
🏁 AbstractCoroutine.resumeWith() → 处理最终结果
↓
📊 makeCompletingOnce() → 状态转换为完成
↓
🎉 协程执行完毕
核心源码详细实现
CoroutineScope.launch
入口源码
// 源码位置:kotlinx.coroutines/Builders.common.kt
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
// 🔧 步骤1:创建新的协程上下文
val newContext = newCoroutineContext(context)
// 🏭 步骤2:根据启动模式创建协程实例
val coroutine = if (start.isLazy)
LazyStandaloneCoroutine(newContext, block) else
StandaloneCoroutine(newContext, active = true)
// 🚀 步骤3:启动协程
coroutine.start(start, coroutine, block)
return coroutine
}
// 🔧 上下文创建详细逻辑
public actual fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext {
// 合并父协程上下文和传入的上下文
val combined = coroutineContext.foldCopiesForChildCoroutine() + context
// DEBUG模式添加协程ID
val debug = if (DEBUG) combined + CoroutineId(COROUTINE_ID.incrementAndGet()) else combined
// 如果没有指定调度器,使用默认调度器
return if (combined !== Dispatchers.Default && combined[ContinuationInterceptor] == null)
debug + Dispatchers.Default else debug
}
StandaloneCoroutine
协程实例创建
// 源码位置:kotlinx.coroutines/Builders.common.kt
private open class StandaloneCoroutine(
parentContext: CoroutineContext,
active: Boolean
) : AbstractCoroutine<Unit>(parentContext, initParentJob = true, active = active) {
// 🛡️ 实现异常处理策略 - 直接传播到全局异常处理器
override fun handleJobException(exception: Throwable): Boolean {
handleCoroutineException(context, exception)
return true // 表示异常已被处理,不会向上传播
}
}
// 🌍 全局异常处理逻辑
internal fun handleCoroutineException(context: CoroutineContext, exception: Throwable) {
try {
// 查找协程异常处理器
context[CoroutineExceptionHandler]?.let {
it.handleException(context, exception)
return
}
} catch (t: Throwable) {
// 异常处理器本身抛出异常
handleCoroutineExceptionImpl(context, handlerException(exception, t))
return
}
// 没有找到处理器,使用默认处理
handleCoroutineExceptionImpl(context, exception)
}
AbstractCoroutine
抽象基类核心
// 源码位置:kotlinx.coroutines/AbstractCoroutine.kt
public abstract class AbstractCoroutine<in T>(
parentContext: CoroutineContext,
initParentJob: Boolean,
active: Boolean
) : JobSupport(active), Job, Continuation<T>, CoroutineScope {
// 🔗 协程上下文 = 父上下文 + 当前Job
public final override val context: CoroutineContext = parentContext + this
public override val coroutineContext: CoroutineContext get() = context
init {
// 🔗 建立父子协程关系
if (initParentJob) initParentJob(parentContext[Job])
}
// 🚀 启动协程的核心方法
public fun <R> start(start: CoroutineStart, receiver: R, block: suspend R.() -> T) {
start(block, receiver, this)
}
// 📞 Continuation接口实现 - 处理协程完成回调
public final override fun resumeWith(result: Result<T>) {
// 🔄 尝试将协程状态转换为完成状态
val state = makeCompletingOnce(result.toState())
if (state === COMPLETING_WAITING_CHILDREN) return // 等待子协程完成
afterResume(state) // 执行完成后的清理工作
}
// 🔄 结果转换为内部状态
private fun Result<T>.toState(): Any? = fold(
onSuccess = { if (it == null) NULL else it },
onFailure = { CompletedExceptionally(it) }
)
// 🎯 子类必须实现的异常处理策略
protected open fun handleJobException(exception: Throwable): Boolean = false
// 🎭 生命周期钩子方法
protected open fun onCompleted(value: T) {}
protected open fun onCancelled(cause: Throwable, handled: Boolean) {}
}
CoroutineStart
启动策略详细实现
// 源码位置:kotlinx.coroutines/CoroutineStart.kt
public enum class CoroutineStart {
/**
* 🔄 默认启动模式:立即调度执行,可以被取消
*/
DEFAULT,
/**
* 💤 懒启动模式:直到需要时才启动
*/
LAZY,
/**
* ⚛️ 原子启动模式:立即执行,启动过程不可取消
*/
ATOMIC,
/**
* 🏃 非调度启动模式:在当前线程立即执行直到第一个挂起点
*/
UNDISPATCHED;
public val isLazy: Boolean get() = this === LAZY
// 📋 策略模式核心方法 - 根据不同策略执行不同启动逻辑
public operator fun <R, T> invoke(
block: suspend R.() -> T,
receiver: R,
completion: Continuation<T>
): Unit = when (this) {
DEFAULT -> block.startCoroutineCancellable(receiver, completion)
LAZY -> Unit // 懒启动不执行任何操作
ATOMIC -> block.startCoroutine(receiver, completion)
UNDISPATCHED -> block.startCoroutineUndispatched(receiver, completion)
}
}
startCoroutineCancellable
可取消启动核心
// 源码位置:kotlinx.coroutines/Cancellable.kt
internal fun <R, T> (suspend (R) -> T).startCoroutineCancellable(
receiver: R,
completion: Continuation<T>,
onCancellation: ((cause: Throwable) -> Unit)? = null
) = runSafely(completion) {
// 🔗 创建状态机 → 添加拦截器 → 开始执行
createCoroutineUnintercepted(receiver, completion)
.intercepted()
.resumeCancellableWith(Result.success(Unit), onCancellation)
}
// 🛡️ 异常安全包装 - 确保启动过程中的异常被正确处理
private inline fun runSafely(completion: Continuation<*>, block: () -> Unit) {
try {
block()
} catch (e: Throwable) {
// 启动失败,直接通知completion
completion.resumeWith(Result.failure(e))
}
}
createCoroutineUnintercepted
状态机创建
// 源码位置:kotlin.coroutines.intrinsics/Intrinsics.kt
public actual fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> {
val probeCompletion = probeCoroutineCreated(completion)
return if (this is BaseContinuationImpl)
// 🏭 如果是编译器生成的状态机,调用create方法
create(receiver, probeCompletion)
else {
// 🔧 否则创建包装器
createCoroutineFromSuspendFunction(probeCompletion) {
(this as Function2<R, Continuation<T>, Any?>).invoke(receiver, it)
}
}
}
intercepted
调度器拦截详细实现
// 源码位置:kotlin.coroutines/Continuation.kt
public actual fun <T> Continuation<T>.intercepted(): Continuation<T> =
(this as? ContinuationImpl)?.intercepted() ?: this
// 源码位置:kotlin.coroutines.jvm.internal/ContinuationImpl.kt
public fun intercepted(): Continuation<Any?> =
intercepted ?: (context[ContinuationInterceptor]?.interceptContinuation(this) ?: this)
.also { intercepted = it }
// 🎯 CoroutineDispatcher 拦截实现
public abstract class CoroutineDispatcher :
AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
// 📦 包装原始continuation为DispatchedContinuation
public final override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
DispatchedContinuation(this, continuation)
}
DispatchedContinuation
线程调度包装
// 源码位置:kotlinx.coroutines.internal/DispatchedContinuation.kt
internal class DispatchedContinuation<in T>(
@JvmField val dispatcher: CoroutineDispatcher,
@JvmField val continuation: Continuation<T>
) : DispatchedTask<T>(MODE_UNINITIALIZED), CoroutineStackFrame, Continuation<T> {
override val delegate: Continuation<T> get() = continuation
// 📞 可取消恢复方法
inline fun resumeCancellableWith(
result: Result<T>,
noinline onCancellation: ((cause: Throwable) -> Unit)?
) {
val state = result.toState(onCancellation)
// ❓ 判断是否需要线程调度
if (dispatcher.isDispatchNeeded(context)) {
// ✅ 需要调度:设置状态并派发到目标线程
_state = state
resumeMode = MODE_CANCELLABLE
dispatcher.dispatch(context, this)
} else {
// ❌ 不需要调度:直接在当前线程执行
executeUnconfined(state, MODE_CANCELLABLE) {
if (!resumeCancelled(state)) {
resumeUndispatchedWith(result)
}
}
}
}
// 🎯 线程调度后的执行入口
override fun resumeWith(result: Result<T>) {
val context = continuation.context
val state = result.toState()
if (dispatcher.isDispatchNeeded(context)) {
_state = state
resumeMode = MODE_ATOMIC
dispatcher.dispatch(context, this)
} else {
executeUnconfined(state, MODE_ATOMIC) {
withCoroutineContext(this.context, countOrElement) {
// 🔄 最终调用原始continuation
continuation.resumeWith(result)
}
}
}
}
}
// 🧵 DispatchedTask 任务执行基类
internal abstract class DispatchedTask<in T>(
@JvmField public var resumeMode: Int
) : SchedulerTask() {
// 🏃 在目标线程中执行的run方法
public final override fun run() {
assert { resumeMode != MODE_UNINITIALIZED }
val taskContext = this.taskContext
var fatalException: Throwable? = null
try {
val delegate = delegate as Continuation<T>
val continuation = delegate.intercepted()
// 🔄 恢复协程执行
withContinuationContext(continuation, countOrElement) {
val context = continuation.context
val state = takeState() // 获取保存的状态
val exception = getExceptionalResult(state)
val job = if (exception == null && resumeMode.isCancellableMode)
context[Job]
else
null
if (job != null && !job.isActive) {
// 协程已被取消
val cause = job.getCancellationException()
cancelCompletedResult(state, cause)
continuation.resumeWithStackTrace(Result.failure(cause))
} else {
// 正常恢复执行
if (exception != null) {
continuation.resumeWith(Result.failure(exception))
} else {
continuation.resumeWith(Result.success(getSuccessfulResult(state)))
}
}
}
} catch (e: Throwable) {
fatalException = e
} finally {
val result = runCatching { taskContext.afterTask() }
handleFatalException(fatalException, result.exceptionOrNull())
}
}
}
CoroutineDispatcher
协程调度器核心流程
📱 Dispatchers.Main 核心实现
// 📱 Android 主线程调度器 - 核心实现
internal class HandlerDispatcher(
private val handler: Handler // 主线程的 Handler
) : CoroutineDispatcher() {
// 🔍 是否需要调度到主线程
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
return Looper.myLooper() != handler.looper // 不在主线程则需要调度
}
// 🎯 派发到主线程 - 核心方法
override fun dispatch(context: CoroutineContext, block: Runnable) {
handler.post(block) // 通过 Handler 切换到主线程
}
}
// 🏭 主线程调度器的创建
object Dispatchers {
val Main = HandlerDispatcher(Handler(Looper.getMainLooper()))
}
🏭 Dispatchers.IO 核心实现
// 🏭 IO 调度器 - 核心实现
object Dispatchers {
val IO = DefaultScheduler.IO // IO 调度器
val Default = DefaultScheduler // 默认调度器
}
// 🧵 默认调度器 - 基于线程池
internal object DefaultScheduler : SchedulerCoroutineDispatcher() {
// 🔧 IO 调度器:限制并发数为 64
val IO = LimitingDispatcher(this, 64, "Dispatchers.IO")
}
// 🚧 限制并发的 IO 调度器
private class LimitingDispatcher(
private val dispatcher: CoroutineDispatcher, // 底层调度器
private val parallelism: Int // 最大并发数 64
) : CoroutineDispatcher() {
private val inFlightTasks = atomic(0) // 当前执行任务数
private val queue = ConcurrentLinkedQueue<Runnable>() // 等待队列
override fun dispatch(context: CoroutineContext, block: Runnable) {
if (inFlightTasks.incrementAndGet() <= parallelism) {
// ✅ 有空闲线程,直接执行
dispatcher.dispatch(context, wrapTask(block))
} else {
// ❌ 线程池满,放入队列等待
inFlightTasks.decrementAndGet()
queue.offer(block)
}
}
private fun wrapTask(block: Runnable) = Runnable {
try {
block.run() // 执行任务
} finally {
inFlightTasks.decrementAndGet() // 任务完成,释放槽位
tryScheduleNext() // 尝试执行队列中的下一个任务
}
}
}
// 🧵 底层线程池调度器
internal class SchedulerCoroutineDispatcher : CoroutineDispatcher() {
private val coroutineScheduler = CoroutineScheduler() // 协程专用线程池
override fun dispatch(context: CoroutineContext, block: Runnable) {
coroutineScheduler.dispatch(block) // 提交到线程池
}
}
// 🏭 协程专用线程池
internal class CoroutineScheduler : Executor {
private val workers = Array<Worker?>(corePoolSize) { null } // 工作线程数组
fun dispatch(block: Runnable) {
val worker = getCurrentWorker() ?: createWorker()
worker.submitTask(block) // 提交任务给工作线程
}
// 🧵 工作线程
private inner class Worker : Thread() {
override fun run() {
while (!isTerminated) {
val task = takeTask() // 获取任务
if (task != null) {
task.run() // 🎯 执行用户的 block 代码
}
}
}
}
}
🔄 核心调度流程
// 📊 完整的调度流程
class CoreDispatchFlow {
// 🎯 Main 线程调度流程
fun mainDispatchFlow() {
// 用户代码
launch(Dispatchers.Main) {
updateUI() // 这个 block 需要在主线程执行
}
// 内部流程:
// 1. DispatchedContinuation.dispatch(Dispatchers.Main, block)
// 2. HandlerDispatcher.dispatch(context, block)
// 3. handler.post(block)
// 4. block 在主线程的消息队列中执行
// 5. updateUI() 在主线程执行
}
// 🎯 IO 线程调度流程
fun ioDispatchFlow() {
// 用户代码
launch(Dispatchers.IO) {
readFile() // 这个 block 需要在 IO 线程执行
}
// 内部流程:
// 1. DispatchedContinuation.dispatch(Dispatchers.IO, block)
// 2. LimitingDispatcher.dispatch(context, block)
// 3. DefaultScheduler.dispatch(context, wrapTask(block))
// 4. CoroutineScheduler.dispatch(wrapTask(block))
// 5. Worker.submitTask(wrapTask(block))
// 6. wrapTask(block).run() 在工作线程执行
// 7. readFile() 在 IO 线程执行
}
}
调度器 | 底层实现 | 线程类型 | 并发限制 | 主要用途 |
---|---|---|---|---|
Dispatchers.Main | Handler + Looper | 主线程 | 单线程 | UI 更新 |
Dispatchers.IO | ThreadPool + 限制器 | 工作线程 | 64 并发 | IO 操作 |
Dispatchers.Default | ThreadPool | 工作线程 | CPU 核心数 | CPU 计算 |
🎯 调度器本质 = isDispatchNeeded() + dispatch()
🎯 Main = Handler.post()
切换到主线程
🎯 IO
= 线程池 + 64
并发限制
🎯 任务执行 = Worker 线程的 task.run()
BaseContinuationImpl
状态机执行核心
// 源码位置:kotlin.coroutines.jvm.internal/ContinuationImpl.kt
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!!
// 获取下一个continuation
val outcome: Result<Any?> =
try {
// ⚙️ 调用状态机的核心方法
val outcome = invokeSuspend(param)
if (outcome === COROUTINE_SUSPENDED) return // 遇到挂起点,退出循环
Result.success(outcome)
} catch (exception: Throwable) {
Result.failure(exception)
}
releaseIntercepted() // 🧹 释放拦截器资源
if (completion is BaseContinuationImpl) {
// 🔄 优化:如果下一个completion也是状态机,继续循环
current = completion
param = outcome
} else {
// 🏁 到达终点:调用最终的completion
completion.resumeWith(outcome)
return
}
}
}
}
// 🎯 抽象方法:子类(编译器生成的状态机)必须实现
protected abstract fun invokeSuspend(result: Result<Any?>): Any?
// 🔗 拦截器支持
public open fun intercepted(): Continuation<Any?> = this
protected open fun releaseIntercepted() {}
}
AbstractCoroutine
处理最终结果
// 🏁 AbstractCoroutine 处理协程完成
public abstract class AbstractCoroutine<in T>(
parentContext: CoroutineContext,
initParentJob: Boolean,
active: Boolean
) : JobSupport(active), Job, Continuation<T> {
// 🎯 处理协程的最终结果
public final override fun resumeWith(result: Result<T>) {
val state = makeCompletingOnce(result)
if (state === COMPLETING_WAITING_CHILDREN) return
afterResume(state)
}
// 📊 状态转换为完成
private fun makeCompletingOnce(proposedUpdate: Any?): Any? {
loopOnState { state ->
val update = when (state) {
is Incomplete -> {
// 🔄 从未完成状态转换为完成状态
when (proposedUpdate) {
is Result.Success -> proposedUpdate.value
is Result.Failure -> CompletedExceptionally(proposedUpdate.exception)
else -> proposedUpdate
}
}
else -> return state // 已经完成
}
// 🔒 原子性状态更新
if (tryMakeCompleting(state, update)) {
return finishCompletion(state, update)
}
}
}
// 🎯 尝试转换为完成状态
private fun tryMakeCompleting(state: Incomplete, update: Any?): Boolean {
if (!state.isActive) return false
// 📝 更新协程状态
val finalState = when (update) {
is CompletedExceptionally -> update
else -> update ?: COMPLETED_SUCCESSFULLY
}
// 🔒 CAS 操作更新状态
return _state.compareAndSet(state, finalState)
}
// 🏆 完成协程的最终处理
private fun finishCompletion(state: Incomplete, update: Any?): Any? {
// 📢 通知父协程和子协程
val parentJob = parentContext[Job]
if (parentJob != null) {
parentJob.childCompleted(this, state, update)
}
// 🧹 清理资源
afterCompletion(update)
// 📊 返回最终状态
return when (update) {
is CompletedExceptionally -> update
else -> COMPLETED_SUCCESSFULLY
}
}
// 🧹 完成后的清理工作
protected open fun afterCompletion(state: Any?) {
// 通知完成回调,可以通过取消子协程、清理资源等
// Job.invokeOnCompletion {}可以收到协程执行完的回调
}
}