Kotlin協(xié)程到底是如何切換線程的
隨著kotlin在Android開發(fā)領(lǐng)域越來越火,協(xié)程在各個(gè)項(xiàng)目中的應(yīng)用也逐漸變得廣泛
但是協(xié)程到底是什么呢?
協(xié)程其實(shí)是個(gè)古老的概念,已經(jīng)非常成熟了,但大家對(duì)它的概念一直存在各種疑問,眾說紛紛
有人說協(xié)程是輕量級(jí)的線程,也有人說kotlin協(xié)程其實(shí)本質(zhì)是一套線程切換方案
顯然這對(duì)初學(xué)者不太友好,當(dāng)不清楚一個(gè)東西是什么的時(shí)候,就很難進(jìn)入為什么和怎么辦的階段了
本文主要就是回答這個(gè)問題,主要包括以下內(nèi)容
1.關(guān)于協(xié)程的一些前置知識(shí)
2.協(xié)程到底是什么?
3.kotlin協(xié)程的一些基本概念,掛起函數(shù),CPS轉(zhuǎn)換,狀態(tài)機(jī)等
以上問題總結(jié)為思維導(dǎo)圖如下:

1. 前置知識(shí)
1.1 CoroutineScope到底是什么?
CoroutineScope即協(xié)程運(yùn)行的作用域,它的源碼很簡單
public interface CoroutineScope {
public val coroutineContext: CoroutineContext
}
可以看出CoroutineScope的代碼很簡單,主要作用是提供CoroutineContext,協(xié)程運(yùn)行的上下文
我們常見的實(shí)現(xiàn)有GlobalScope,LifecycleScope,ViewModelScope等
1.2 GlobalScope與ViewModelScope有什么區(qū)別?
public object GlobalScope : CoroutineScope {
/**
* 返回 [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
public val ViewModel.viewModelScope: CoroutineScope
get() {
val scope: CoroutineScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(
JOB_KEY,
CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
)
}
兩者的代碼都挺簡單,從上面可以看出
1.GlobalScope返回的為CoroutineContext的空實(shí)現(xiàn)
2.ViewModelScope則往CoroutineContext中添加了Job與Dispatcher
我們先來看一段簡單的代碼
fun testOne(){
GlobalScope.launch {
print("1:" + Thread.currentThread().name)
delay(1000)
print("2:" + Thread.currentThread().name)
}
}
//打印結(jié)果為:DefaultDispatcher-worker-1
fun testTwo(){
viewModelScope.launch {
print("1:" + Thread.currentThread().name)
delay(1000)
print("2:" + Thread.currentThread().name)
}
}
//打印結(jié)果為: main
上面兩種Scope啟動(dòng)協(xié)程后,打印當(dāng)前線程名是不同的,一個(gè)是線程池中的一個(gè)線程,一個(gè)則是主線程
這是因?yàn)?code>ViewModelScope在CoroutineContext中添加了Dispatchers.Main.immediate的原因
我們可以得出結(jié)論:協(xié)程就是通過Dispatchers調(diào)度器來控制線程切換的
1.3 什么是調(diào)度器?
從使用上來講,調(diào)度器就是我們使用的Dispatchers.Main,Dispatchers.Default,Dispatcher.IO等
從作用上來講,調(diào)度器的作用是控制協(xié)程運(yùn)行的線程
從結(jié)構(gòu)上來講,Dispatchers的父類是ContinuationInterceptor,然后再繼承于CoroutineContext
它們的類結(jié)構(gòu)關(guān)系如下:

這也是為什么Dispatchers能加入到CoroutineContext中的原因,并且支持+操作符來完成增加
1.4 什么是攔截器
從命名上很容易看出,ContinuationInterceptor即協(xié)程攔截器,先看一下接口
interface ContinuationInterceptor : CoroutineContext.Element {
// ContinuationInterceptor 在 CoroutineContext 中的 Key
companion object Key : CoroutineContext.Key<ContinuationInterceptor>
/**
* 攔截 continuation
*/
fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T>
//...
}
從上面可以提煉出兩個(gè)信息
1.攔截器的Key是單例的,因此當(dāng)你添加多個(gè)攔截器時(shí),生效的只會(huì)有一個(gè)
2.我們都知道,Continuation在調(diào)用其Continuation#resumeWith()方法,會(huì)執(zhí)行其suspend修飾的函數(shù)的代碼塊,如果我們提前攔截到,是不是可以做點(diǎn)其他事情?這就是調(diào)度器切換線程的原理
上面我們已經(jīng)介紹了是通過Dispatchers指定協(xié)程運(yùn)行的線程,通過interceptContinuation在協(xié)程恢復(fù)前進(jìn)行攔截,從而切換線程
帶著這些前置知識(shí),我們一起來看下協(xié)程啟動(dòng)的具體流程,明確下協(xié)程切換線程源碼具體實(shí)現(xiàn)
2. 協(xié)程線程切換源碼分析
2.1 launch方法解析
我們首先看一下協(xié)程是怎樣啟動(dòng)的,傳入了什么參數(shù)
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
val newContext = newCoroutineContext(context)
val coroutine = if (start.isLazy)
LazyStandaloneCoroutine(newContext, block) else
StandaloneCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
return coroutine
}
總共有3個(gè)參數(shù):
1.傳入的協(xié)程上下文
2.CoroutinStart啟動(dòng)器,是個(gè)枚舉類,定義了不同的啟動(dòng)方法,默認(rèn)是CoroutineStart.DEFAULT
3.block就是我們傳入的協(xié)程體,真正要執(zhí)行的代碼
這段代碼主要做了兩件事:
1.組合新的CoroutineContext
2.再創(chuàng)建一個(gè) Continuation
2.1.1 組合新的CoroutineContext
public actual fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext {
val combined = coroutineContext + context
val debug = if (DEBUG) combined + CoroutineId(COROUTINE_ID.incrementAndGet()) else combined
return if (combined !== Dispatchers.Default && combined[ContinuationInterceptor] == null)
debug + Dispatchers.Default else debug
}
從上面可以提煉出以下信息:
1.會(huì)將launch方法傳入的context與CoroutineScope中的context組合起來
2.如果combined中沒有攔截器,會(huì)傳入一個(gè)默認(rèn)的攔截器,即Dispatchers.Default,這也解釋了為什么我們沒有傳入攔截器時(shí)會(huì)有一個(gè)默認(rèn)切換線程的效果
2.1.2 創(chuàng)建一個(gè)Continuation
val coroutine = if (start.isLazy)
LazyStandaloneCoroutine(newContext, block) else
StandaloneCoroutine(newContext, active = true)
coroutine.start(start, coroutine, block)
默認(rèn)情況下,我們會(huì)創(chuàng)建一個(gè)StandloneCoroutine
值得注意的是,這個(gè)coroutine其實(shí)是我們協(xié)程體的complete,即成功后的回調(diào),而不是協(xié)程體本身
然后調(diào)用coroutine.start,這表明協(xié)程開始啟動(dòng)了
2.2 協(xié)程的啟動(dòng)
public fun <R> start(start: CoroutineStart, receiver: R, block: suspend R.() -> T) {
initParentJob()
start(block, receiver, this)
}
接著調(diào)用CoroutineStart的start來啟動(dòng)協(xié)程,默認(rèn)情況下調(diào)用的是CoroutineStart.Default
經(jīng)過層層調(diào)用,最后到達(dá)了:
internal fun <R, T> (suspend (R) -> T).startCoroutineCancellable(receiver: R, completion: Continuation<T>) =
runSafely(completion) {
// 外面再包一層 Coroutine
createCoroutineUnintercepted(receiver, completion)
// 如果需要,做攔截處理
.intercepted()
// 調(diào)用 resumeWith 方法
.resumeCancellableWith(Result.success(Unit))
}
這里就是協(xié)程啟動(dòng)的核心代碼,雖然比較短,卻包括3個(gè)步驟:
1.創(chuàng)建協(xié)程體Continuation
2.創(chuàng)建攔截 Continuation,即DispatchedContinuation
3.執(zhí)行DispatchedContinuation.resumeWith方法
2.3 創(chuàng)建協(xié)程體Continuation
調(diào)用createCoroutineUnintercepted,會(huì)把我們的協(xié)程體即suspend block轉(zhuǎn)換成Continuation,它是SuspendLambda,繼承自ContinuationImpl
createCoroutineUnintercepted方法在源碼中找不到具體實(shí)現(xiàn),不過如果你把協(xié)程體代碼反編譯后就可以看到真正的實(shí)現(xiàn)
詳情可見:字節(jié)碼反編譯
2.4 創(chuàng)建DispatchedContinuation
public actual fun <T> Continuation<T>.intercepted(): Continuation<T> =
(this as? ContinuationImpl)?.intercepted() ?: this
//ContinuationImpl
public fun intercepted(): Continuation<Any?> =
intercepted
?: (context[ContinuationInterceptor]?.interceptContinuation(this) ?: this)
.also { intercepted = it }
//CoroutineDispatcher
public final override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
DispatchedContinuation(this, continuation)
從上可以提煉出以下信息
1.interepted是個(gè)擴(kuò)展方法,最后會(huì)調(diào)用到ContinuationImpl.intercepted方法
2.在intercepted會(huì)利用CoroutineContext,獲取當(dāng)前的攔截器
3.因?yàn)楫?dāng)前的攔截器是CoroutineDispatcher,因此最終會(huì)返回一個(gè)DispatchedContinuation,我們其實(shí)也是利用它實(shí)現(xiàn)線程切換的
4.我們將協(xié)程體的Continuation傳入DispatchedContinuation,這里其實(shí)用到了裝飾器模式,實(shí)現(xiàn)功能的增強(qiáng)

這里其實(shí)很明顯了,通過DispatchedContinuation裝飾原有協(xié)程,在DispatchedContinuation里通過調(diào)度器處理線程切換,不影響原有邏輯,實(shí)現(xiàn)功能的增強(qiáng)
2.5 攔截處理
//DispatchedContinuation
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)
}
}
}
}
上面說到了啟動(dòng)時(shí)會(huì)調(diào)用DispatchedContinuation的resumeCancellableWith方法
這里面做的事也很簡單:
1.如果需要切換線程,調(diào)用dispatcher.dispatcher方法,這里的dispatcher是通過CoroutineConext取出來的
2.如果不需要切換線程,直接運(yùn)行原有線程即可
2.5.2 調(diào)度器的具體實(shí)現(xiàn)
我們首先明確下,CoroutineDispatcher是通過CoroutineContext取出來的,這也是協(xié)程上下文作用的體現(xiàn)
CoroutineDispater官方提供了四種實(shí)現(xiàn):Dispatchers.Main,Dispatchers.IO,Dispatchers.Default,Dispatchers.Unconfined
我們一起簡單看下Dispatchers.Main的實(shí)現(xiàn)
internal class HandlerContext private constructor(
private val handler: Handler,
private val name: String?,
private val invokeImmediately: Boolean
) : HandlerDispatcher(), Delay {
public constructor(
handler: Handler,
name: String? = null
) : this(handler, name, false)
//...
override fun dispatch(context: CoroutineContext, block: Runnable) {
// 利用主線程的 Handler 執(zhí)行任務(wù)
handler.post(block)
}
}
可以看到,其實(shí)就是用handler切換到了主線程
如果用Dispatcers.IO也是一樣的,只不過換成線程池切換了

如上所示,其實(shí)就是一個(gè)裝飾模式
1.調(diào)用CoroutinDispatcher.dispatch方法切換線程
2.切換完成后調(diào)用DispatchedTask.run方法,執(zhí)行真正的協(xié)程體
3 delay是怎樣切換線程的?
上面我們介紹了協(xié)程線程調(diào)度的基本原理與實(shí)現(xiàn),下面我們來回答幾個(gè)小問題
我們知道delay函數(shù)會(huì)掛起,然后等待一段時(shí)間再恢復(fù)。
可以想象,這里面應(yīng)該也涉及到線程的切換,具體是怎么實(shí)現(xiàn)的呢?
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
// if timeMillis == Long.MAX_VALUE then just wait forever like awaitCancellation, don't schedule.
if (timeMillis < Long.MAX_VALUE) {
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
}
internal val CoroutineContext.delay: Delay get() = get(ContinuationInterceptor) as? Delay ?: DefaultDelay
Dealy的代碼也很簡單,從上面可以提煉出以下信息
delay的切換也是通過攔截器來實(shí)現(xiàn)的,內(nèi)置的攔截器同時(shí)也實(shí)現(xiàn)了Delay接口
我們來看一個(gè)具體實(shí)現(xiàn)
internal class HandlerContext private constructor(
private val handler: Handler,
private val name: String?,
private val invokeImmediately: Boolean
) : HandlerDispatcher(), Delay {
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
// 利用主線程的 Handler 延遲執(zhí)行任務(wù),將完成的 continuation 放在任務(wù)中執(zhí)行
val block = Runnable {
with(continuation) { resumeUndispatched(Unit) }
}
handler.postDelayed(block, timeMillis.coerceAtMost(MAX_DELAY))
continuation.invokeOnCancellation { handler.removeCallbacks(block) }
}
//..
}
1.可以看出,其實(shí)也是通過handler.postDelayed實(shí)現(xiàn)延時(shí)效果的
2.時(shí)間到了之后,再通過resumeUndispatched方法恢復(fù)協(xié)程
3.如果我們用的是Dispatcher.IO,效果也是一樣的,不同的就是延時(shí)效果是通過切換線程實(shí)現(xiàn)的
4. withContext是怎樣切換線程的?
我們?cè)趨f(xié)程體內(nèi),可能通過withContext方法簡單便捷的切換線程,用同步的方式寫異步代碼,這也是kotin協(xié)程的主要優(yōu)勢(shì)之一
fun test(){
viewModelScope.launch(Dispatchers.Main) {
print("1:" + Thread.currentThread().name)
withContext(Dispatchers.IO){
delay(1000)
print("2:" + Thread.currentThread().name)
}
print("3:" + Thread.currentThread().name)
}
}
//1,2,3處分別輸出main,DefaultDispatcher-worker-1,main
可以看出這段代碼做了一個(gè)切換線程然后再切換回來的操作,我們可以提出兩個(gè)問題
1.withContext是怎樣切換線程的?
2.withContext內(nèi)的協(xié)程體結(jié)束后,線程怎樣切換回到Dispatchers.Main?
public suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T {
return suspendCoroutineUninterceptedOrReturn sc@ { uCont ->
// 創(chuàng)建新的context
val oldContext = uCont.context
val newContext = oldContext + context
....
//使用新的Dispatcher,覆蓋外層
val coroutine = DispatchedCoroutine(newContext, uCont)
coroutine.initParentJob()
//DispatchedCoroutine作為了complete傳入
block.startCoroutineCancellable(coroutine, coroutine)
coroutine.getResult()
}
}
private class DispatchedCoroutine<in T>(
context: CoroutineContext,
uCont: Continuation<T>
) : ScopeCoroutine<T>(context, uCont) {
//在complete時(shí)會(huì)會(huì)回調(diào)
override fun afterCompletion(state: Any?) {
afterResume(state)
}
override fun afterResume(state: Any?) {
//uCont就是父協(xié)程,context仍是老版context,因此可以切換回原來的線程上
uCont.intercepted().resumeCancellableWith(recoverResult(state, uCont))
}
}
這段代碼其實(shí)也很簡單,可以提煉出以下信息
1.withContext其實(shí)就是一層Api封裝,最后調(diào)用到了startCoroutineCancellable,這就跟launch后面的流程一樣了,我們就不繼續(xù)跟了
2.傳入的context會(huì)覆蓋外層的攔截器并生成一個(gè)newContext,因此可以實(shí)現(xiàn)線程的切換
3.DispatchedCoroutine作為complete傳入?yún)f(xié)程體的創(chuàng)建函數(shù)中,因此協(xié)程體執(zhí)行完成后會(huì)回調(diào)到afterCompletion中
4.DispatchedCoroutine中傳入的uCont是父協(xié)程,它的攔截器仍是外層的攔截器,因此會(huì)切換回原來的線程中
總結(jié)
本文主要回答了kotlin協(xié)程到底是怎么切換線程的這個(gè)問題,并對(duì)源碼進(jìn)行了分析
簡單來講主要包括以下步驟:
1.向CoroutineContext添加Dispatcher,指定運(yùn)行的協(xié)程
2.在啟動(dòng)時(shí)將suspend block創(chuàng)建成Continuation,并調(diào)用intercepted生成DispatchedContinuation
3.DispatchedContinuation就是對(duì)原有協(xié)程的裝飾,在這里調(diào)用Dispatcher完成線程切換任務(wù)后,resume被裝飾的協(xié)程,就會(huì)執(zhí)行協(xié)程體內(nèi)的代碼了
其實(shí)kotlin協(xié)程就是用裝飾器模式實(shí)現(xiàn)線程切換的
看起來似乎有不少代碼,但是真正的思路其實(shí)還是挺簡單的,這大概就是設(shè)計(jì)模式的作用吧
最后
小編分享一些 Android 開發(fā)相關(guān)的學(xué)習(xí)文檔、面試題、Android 核心筆記等等文檔,希望能幫助到大家學(xué)習(xí)提升,如有需要參考的可以直接去我 CodeChina地址:https://codechina.csdn.net/u012165769/Android-T3 訪問查閱。如果本文對(duì)你有所幫助,歡迎點(diǎn)贊收藏~
到此這篇關(guān)于Kotlin協(xié)程到底是如何切換線程的的文章就介紹到這了,更多相關(guān)協(xié)程切換線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android下拉刷新ListView——RTPullListView(demo)
下拉刷新已經(jīng)形成一種默認(rèn)的用戶習(xí)慣,今天主要介紹下在Android上實(shí)現(xiàn)下拉刷新的Demo,感興趣的朋友可以參考下哈,希望可以幫助到你2013-04-04
Android系統(tǒng)聯(lián)系人全特效實(shí)現(xiàn)(上)分組導(dǎo)航和擠壓動(dòng)畫(附源碼)
本文將為大家講解下Android系統(tǒng)聯(lián)系人全特效實(shí)現(xiàn)之分組導(dǎo)航和擠壓動(dòng)畫,具體實(shí)現(xiàn)及源代碼如下,感興趣的朋友可以參考下哈,希望對(duì)大家學(xué)習(xí)有所幫助2013-06-06
Android賬號(hào)注冊(cè)實(shí)現(xiàn)點(diǎn)擊獲取驗(yàn)證碼倒計(jì)時(shí)效果
這篇文章主要為大家詳細(xì)介紹了Android賬號(hào)注冊(cè)過程中實(shí)現(xiàn)點(diǎn)擊獲取驗(yàn)證碼倒計(jì)時(shí)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
Android實(shí)現(xiàn)雅虎新聞?wù)虞d視差動(dòng)畫效果
這篇文章主要介紹了Android實(shí)現(xiàn)雅虎新聞?wù)虞d視差動(dòng)畫效果,通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
Android框架Volley使用之Json請(qǐng)求實(shí)現(xiàn)
這篇文章主要介紹了Android框架Volley使用之Json請(qǐng)求實(shí)現(xiàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-05-05
Android中實(shí)現(xiàn)長按修改ListView對(duì)象的內(nèi)容
這篇文章主要給大家介紹了在Android中實(shí)現(xiàn)長按修改ListView對(duì)象內(nèi)容的相關(guān)資料,文中給出了完整的示例代碼,相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-02-02

