Kotlin 协程
Kotlin 协程教程:详解 suspend 函数、runBlocking/launch/async/coroutineScope/supervisorScope、Dispatchers、取消超时、Flow 与异常处理。
学完这一章,你能够
- Kotlin 协程教程:详解 suspend 函数、runBlocking/launch/async/coroutineScope/supervisorScope、Dispatchers、取消超时、Flow 与异常处理。
协程概念、挂起非阻塞与第一个协程
协程是运行在线程之上的轻量级并发单元,由编译器通过状态机与续体(`Continuation`)实现挂起与恢复,旨在用接近顺序代码的写法解决异步回调嵌套与高成本线程切换问题。核心区分在于「挂起(suspend)不阻塞线程」:当协程等待网络或定时器时主动让出底层线程去执行其他任务,结果就绪后再恢复执行,单线程即可承载大量并发 IO 任务。协程核心语言特性自 Kotlin 1.3 起稳定,高阶并发 API 由官方库 `kotlinx-coroutines` 提供。
入门最常用的构建器是 `runBlocking` 与 `launch`:`runBlocking` 会阻塞当前线程直至其作用域内全部子协程完成,仅应作为 `main` 入口或测试桥接,不可用于服务端业务主路径以免耗尽线程池;`launch` 启动非阻塞的后台协程并返回 `Job` 句柄,允许主协程继续推进并与子协程并发执行。
suspend 函数、结构化并发与调度器 Dispatchers
`suspend` 关键字标记可挂起函数,编译期会为其注入隐式续体参数以保存挂起点状态,因此 `suspend` 函数只能在协程体或其他 `suspend` 函数内调用。结构化并发(Structured Concurrency)要求所有子协程都归属明确作用域,父协程必须等待全部子协程结束,且任一子协程未捕获异常会自动取消兄弟与父协程,从而根除孤儿协程泄漏;`coroutineScope` 在挂起函数内创建遵循整体失败语义的子作用域,而 `supervisorScope` 允许单个子协程失败时不波及兄弟协程。
调度器 `Dispatchers` 控制协程在何种线程池上恢复执行,常用 `withContext(dispatcher)` 在挂起函数内按需切换:`Dispatchers.Default` 面向 CPU 密集计算,`Dispatchers.IO` 面向阻塞式文件/网络/数据库访问(默认并发上限 64,可经系统属性调整),`Dispatchers.Main` 面向 Android/Swing/JavaFX 主线程更新 UI(需对应平台依赖),`Dispatchers.Unconfined` 不限定线程且仅适用于特殊测试场景。
协作式取消、超时控制与 async/await 并发
Kotlin 协程的取消是协作式的:调用 `job.cancel()` 仅将状态置为取消中,协程只有遇到 `delay`、`yield` 等可取消挂起点时才会抛出 `CancellationException` 退出。若协程正在执行密集纯计算循环而无挂起点,必须周期性调用 `ensureActive()` 或检查 `isActive` 响应取消。超时控制提供 `withTimeout`(超时抛出 `TimeoutCancellationException`)与 `withTimeoutOrNull`(超时返回 `null`)。
当需要并行求值并汇总返回结果时使用 `async`,它返回持有结果的 `Deferred<T>` 句柄,调用 `await()` 挂起等待结果就绪。将多个 `async` 放在同一 `coroutineScope` 内即可并行执行并在异常时自动协同取消;切忌在脱离父作用域的全局作用域直接创建孤立 `async`,否则会破坏结构化并发与异常传播。
异步冷流 Flow 与异常处理边界
`Flow`(自 `kotlinx.coroutines` 1.4 稳定)是支持挂起操作的异步数据流,采用与 `Sequence` 类似的惰性冷流模型:通过 `flow { emit(...) }` 声明的数据生产逻辑仅在末端调用 `collect` 时才会按需执行,并可链式组合 `map`、`filter`、`onEach`、`flowOn`(切换上游调度器)与 `catch`(声明式捕获上游异常)。
协程异常处理需严格区分作用域层级:在挂起调用外部可用 `try/catch` 捕获 `coroutineScope` 向上抛出的异常;对于根协程(例如直接挂载在独立 `CoroutineScope(Job() + handler).launch` 上的顶层 `launch`,而非 `runBlocking` 内的普通子 `launch`),可安装 `CoroutineExceptionHandler` 兜底记录未捕获异常。任何通用 `catch (e: Exception)` 代码块都禁止吞掉 `CancellationException`,捕获到取消异常时必须重新抛出以维持结构化取消机制。
依赖引入与协程常见问题排查
协程库独立于标准库发布,Gradle 需声明 `implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.x")`(与 Kotlin 2.x 配套),Maven 的 JVM 项目需引入带 `-jvm` 后缀的 `kotlinx-coroutines-core-jvm` 构件。
高频问题排查:在普通函数直接调用 `suspend` 函数会编译报错,需将调用方改为 `suspend` 或通过协程构建器进入协程;`cancel()` 后协程未停多因计算循环缺少挂起点,应加入 `ensureActive()`/`yield()`;`runBlocking` 阻塞线程用于入口而 `coroutineScope` 仅挂起用于内部并发;纯同步计算流优先 `Sequence`,涉及挂起 IO 选 `Flow`;`Dispatchers.IO` 默认受 64 并发上限保护,不会无限膨胀线程。
常见协程构建器与作用域对比
| 构建器 | 返回值 | 异常行为 | 典型场景 |
| runBlocking | lambda 最终结果 T | 直接向调用线程抛出异常 | main 入口与测试桥接 |
| launch | Job | 未捕获异常向上传播并取消父作用域 | 无需返回值的并发副作用任务 |
| async | Deferred<T> | 封装异常并在 await() 处抛出(同时按结构化取消父级) | 需要并发求值与汇总结果的任务 |
| coroutineScope | lambda 最终结果 T | 任一子协程失败则取消其余子协程并整体抛出 | suspend 函数内部组织并行子任务 |
| supervisorScope | lambda 最终结果 T | 单个子协程失败不自动取消兄弟协程 | 相互独立的子任务并发隔离 |
常用 Dispatchers 调度器对照
| 调度器 | 线程池 | 适用场景 |
| Dispatchers.Default | 共享后台线程池,线程数与 CPU 核心数相当(至少 2) | 排序、JSON 解析、加解密等 CPU 密集型计算 |
| Dispatchers.IO | 按需弹性线程池,默认最大并发 64(可配置) | 阻塞式文件读写、网络请求与数据库查询 |
| Dispatchers.Main | 平台主线程(需引入 Android/Swing/JavaFX 协程库) | 界面状态更新与轻量主线程调度 |
| Dispatchers.Unconfined | 不绑定固定线程池,恢复时沿用挂起点回调线程 | 极少数测试或特殊内部框架场景,业务不推荐使用 |
运行离线 Python asyncio 校验:结构化协程作用域、协作取消与超时、async/Channel 与冷流 Flow/异常边界
展开查看收起
"""Offline Kotlin 2.x semantic verifier for Chapter 37: Coroutines (asyncio model)."""
import asyncio
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
async def _run_structured_and_supervisor():
# 1. launch non-blocking ordering: main continues, B (5ms) finishes before A (20ms)
launch_log = []
async def job_a():
await asyncio.sleep(0.025)
launch_log.append("协程 A 完成")
async def job_b():
await asyncio.sleep(0.005)
launch_log.append("协程 B 完成")
t_a = asyncio.create_task(job_a())
t_b = asyncio.create_task(job_b())
launch_log.append("main 协程继续执行")
await asyncio.gather(t_a, t_b)
# 2. suspend chain
async def fetch_site() -> str:
await asyncio.sleep(0.005)
return "mbsky.cn"
site = await fetch_site()
# 3. structured coroutineScope: parent waits for all children, and failure cancels sibling
scope_log = []
sibling_cancelled = False
async def load_home_page():
async with asyncio.TaskGroup() as tg:
async def mod_a():
await asyncio.sleep(0.020)
scope_log.append("模块 A 加载完成")
async def mod_b():
await asyncio.sleep(0.005)
scope_log.append("模块 B 加载完成")
tg.create_task(mod_a())
tg.create_task(mod_b())
scope_log.append("等待所有子协程……")
scope_log.append("首页全部就绪")
await load_home_page()
try:
async with asyncio.TaskGroup() as tg:
async def failing_child():
await asyncio.sleep(0.005)
raise RuntimeError("child boom")
async def slow_sibling():
nonlocal sibling_cancelled
try:
await asyncio.sleep(0.5)
except asyncio.CancelledError:
sibling_cancelled = True
raise
tg.create_task(failing_child())
tg.create_task(slow_sibling())
except* RuntimeError:
pass
# 4. supervisorScope: sibling survives when one child fails
async def sup_fail():
await asyncio.sleep(0.005)
raise RuntimeError("isolated failure")
async def sup_ok():
await asyncio.sleep(0.015)
return "sibling_survived"
sup_results = await asyncio.gather(sup_fail(), sup_ok(), return_exceptions=True)
return {
"launch_order": launch_log,
"suspend_fetch": site,
"scope_order": scope_log,
"coroutineScope_cancels_sibling": sibling_cancelled,
"supervisorScope_sibling_result": sup_results[1],
"supervisorScope_failed_type": type(sup_results[0]).__name__,
}
def case_suspend_launch_and_structured_scope():
actual = asyncio.run(_run_structured_and_supervisor())
expected = {
"launch_order": ["main 协程继续执行", "协程 B 完成", "协程 A 完成"],
"suspend_fetch": "mbsky.cn",
"scope_order": ["等待所有子协程……", "模块 B 加载完成", "模块 A 加载完成", "首页全部就绪"],
"coroutineScope_cancels_sibling": True,
"supervisorScope_sibling_result": "sibling_survived",
"supervisorScope_failed_type": "RuntimeError",
}
return {
"name": "suspend_launch_and_structured_scope",
"summary": "Verify launch non-blocking order, suspend chain, coroutineScope cancellation, and supervisorScope isolation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_cancellation_and_timeout():
# Cooperative cancellation at suspension point (delay)
downloads = []
async def downloader():
for i in range(5):
await asyncio.sleep(0.012)
downloads.append(f"第 {i} 次下载……")
task = asyncio.create_task(downloader())
await asyncio.sleep(0.030)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# withTimeoutOrNull returns None on timeout
async def with_timeout_or_null(sec: float, coro):
try:
return await asyncio.wait_for(coro, timeout=sec)
except TimeoutError:
return None
timeout_res = await with_timeout_or_null(0.015, asyncio.sleep(0.5, result="下载完成"))
# Cooperative CPU loop using ensureActive() check
cancelled_flag = False
stopped_early = False
def ensure_active():
if cancelled_flag:
raise asyncio.CancelledError()
iterations = 0
try:
for i in range(1, 1000):
iterations = i
if i == 50:
cancelled_flag = True
if i % 10 == 0:
ensure_active()
except asyncio.CancelledError:
stopped_early = True
return {
"job_cancelled": task.cancelled(),
"stopped_before_all_5": len(downloads) < 5,
"timeout_or_null": timeout_res,
"ensure_active_stopped_at": iterations if stopped_early else -1,
}
def case_cancellation_timeout_and_ensure_active():
actual = asyncio.run(_run_cancellation_and_timeout())
expected = {
"job_cancelled": True,
"stopped_before_all_5": True,
"timeout_or_null": None,
"ensure_active_stopped_at": 50,
}
return {
"name": "cancellation_timeout_and_ensure_active",
"summary": "Verify cooperative job.cancel(), withTimeoutOrNull returning None, and ensureActive() in CPU loops",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_async_await_and_channel():
async def load_module(name: str, delay_s: float) -> str:
await asyncio.sleep(delay_s)
return f"{name} 加载完成"
loop = asyncio.get_running_loop()
t0 = loop.time()
d_a = asyncio.create_task(load_module("模块 A", 0.035))
d_b = asyncio.create_task(load_module("模块 B", 0.035))
res_a = await d_a
res_b = await d_b
elapsed = loop.time() - t0
# Channel (bounded Queue) producer -> consumer
channel: asyncio.Queue[int | None] = asyncio.Queue(maxsize=2)
received = []
async def producer():
for x in (10, 20, 30):
await channel.put(x)
await channel.put(None)
async def consumer():
while True:
item = await channel.get()
if item is None:
break
received.append(item)
await asyncio.gather(producer(), consumer())
return {
"deferred_results": [res_a, res_b],
"ran_concurrently": elapsed < 0.065,
"channel_received": received,
}
def case_async_await_and_channel():
actual = asyncio.run(_run_async_await_and_channel())
expected = {
"deferred_results": ["模块 A 加载完成", "模块 B 加载完成"],
"ran_concurrently": True,
"channel_received": [10, 20, 30],
}
return {
"name": "async_await_and_channel",
"summary": "Verify parallel async/await Deferred execution and bounded Channel producer-consumer handoff",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
async def _run_cold_flow_and_exceptions():
# Cold Flow: each collector triggers a fresh execution of the async generator
executions = 0
async def number_flow():
nonlocal executions
executions += 1
for i in range(1, 6):
await asyncio.sleep(0)
yield i
async def flow_map(src, fn):
async for item in src:
yield fn(item)
async def flow_filter(src, pred):
async for item in src:
if pred(item):
yield item
transformed = [
x async for x in flow_filter(flow_map(number_flow(), lambda n: n * 10), lambda n: n > 20)
]
collected = [f"收到:{x}" async for x in number_flow()]
# Flow catch operator catches upstream error and emits fallback
async def risky_flow():
yield "第一项"
raise RuntimeError("数据源断开")
async def catch_flow(src):
try:
async for item in src:
yield item
except Exception as exc:
yield f"捕获到异常:{exc}"
recovered = [x async for x in catch_flow(risky_flow())]
# CoroutineExceptionHandler applies to uncaught root coroutines
handler_msgs = []
async def root_launch(coro, handler):
try:
await coro
except asyncio.CancelledError:
raise
except Exception as exc:
handler(exc)
async def failing_root():
raise RuntimeError("任务失败")
await root_launch(failing_root(), lambda e: handler_msgs.append(f"全局处理:{e}"))
return {
"cold_flow_executions": executions,
"transformed": transformed,
"collected": collected,
"risky_recovered": recovered,
"root_handler": handler_msgs,
}
def case_cold_flow_and_exceptions():
actual = asyncio.run(_run_cold_flow_and_exceptions())
expected = {
"cold_flow_executions": 2,
"transformed": [30, 40, 50],
"collected": ["收到:1", "收到:2", "收到:3", "收到:4", "收到:5"],
"risky_recovered": ["第一项", "捕获到异常:数据源断开"],
"root_handler": ["全局处理:任务失败"],
}
return {
"name": "cold_flow_and_exceptions",
"summary": "Verify cold Flow re-execution, map/filter/catch operators, and root CoroutineExceptionHandler",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_suspend_launch_and_structured_scope(),
case_cancellation_timeout_and_ensure_active(),
case_async_await_and_channel(),
case_cold_flow_and_exceptions(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 CancellationException 是 Exception 的子类,宽泛的 catch (e: Exception) 会把正常取消信号静默吞掉,导致协程无法及时退出并破坏结构化并发;修复方式是在 catch 中显式判断 if (e is CancellationException) throw e(或单独前置 catch (e: CancellationException) { throw e })将取消异常重新抛出。