withContext跨线程返回值为什么不需要volatile

本文最后更新于:2026年3月7日 晚上

我们平常写协程代码时,如下所示,不需要什么volatile,就能获取正确的结果,那么协程是怎么保证我们的跨线程传递变量是安全的?需要从 happens-before 讲起。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
lifecycle.coroutineScope.launch {
var a = 50
val result = withContext(Dispatchers.IO) {
delay(3000)
a++
55
}
Log.e(TAG, "onCreate result: $result a:$a")
}

lifecycle.coroutineScope.launch(Dispatchers.Default) {
var b = 50
val result = withContext(Dispatchers.IO) {
delay(3000)
b++
55
}
Log.e(TAG, "onCreate result: $result b:$b")
}

happens-before原则

main 入队 出队

future 例子

参考


withContext跨线程返回值为什么不需要volatile
https://iwesley.top/article/812f630/
作者
Wesley
发布于
2026年1月25日
许可协议