Kotlin協(xié)程的啟動(dòng)方式介紹
啟動(dòng)協(xié)程的基本方式
1.GlobalScope.launch
代碼示例:
fun testGlobalScope() {
GlobalScope.launch {
println("Coroutinue started!")
delay(1000L)
println("Hello World!")
}
println("After launch!")
Thread.sleep(2000L)
println("Process end!")
}
/**
* After launch!
* Coroutinue started!
* Hello World!
* Process end!
*/@DelicateCoroutinesApi
public object GlobalScope : CoroutineScope {
/**
* Returns [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}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
}launch函數(shù)是CoroutineScope的擴(kuò)展函數(shù),它有三個(gè)參數(shù):
- context: CoroutineContext = EmptyCoroutineContext, 第一個(gè)參數(shù)是協(xié)程上下文,它的默認(rèn)值是 EmptyCoroutineContext,如果不傳這個(gè)參數(shù),默認(rèn)就會(huì)使用 EmptyCoroutineContext。也可以傳入 Kotlin 官方為我們提供的 Dispatchers,來(lái)指定協(xié)程運(yùn)行的線程池。(Dispatchers.IO、Dispatchers.Unconfined、Dispatchers.Main)
- start: CoroutineStart = CoroutineStart.DEFAULT,第二個(gè)參數(shù)是協(xié)程的啟動(dòng)模式,默認(rèn)值是CoroutineStart.DEFAULT,CoroutineStart 是一個(gè)枚舉類(lèi),一共有:DEFAULT、LAZY、ATOMIC、UNDISPATCHED。
- block: suspend CoroutineScope.() -> Unit,第三個(gè)參數(shù)是函數(shù)類(lèi)型block,它的類(lèi)型是suspend CoroutineScope.() -> Unit。本質(zhì)是一個(gè)掛起函數(shù)。
- 函數(shù)的返回值是一個(gè) Job,它其實(shí)代表的是協(xié)程的句柄,并不能返回協(xié)程的執(zhí)行結(jié)果。
2.runBlocking 啟動(dòng)協(xié)程
代碼示例
fun testRunBlocking2() {
runBlocking {
println("Coroutinue started!")
delay(1000L)
println("Hello World!")
}
println("After Launch")
Thread.sleep(2000L)
println("Process end")
}
/**
* Coroutinue started!
* Hello World!
* After Launch
* Process end
*/@Throws(InterruptedException::class)
public actual fun <T> runBlocking(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val currentThread = Thread.currentThread()
val contextInterceptor = context[ContinuationInterceptor]
val eventLoop: EventLoop?
val newContext: CoroutineContext
if (contextInterceptor == null) {
// create or use private event loop if no dispatcher is specified
eventLoop = ThreadLocalEventLoop.eventLoop
newContext = GlobalScope.newCoroutineContext(context + eventLoop)
} else {
// See if context's interceptor is an event loop that we shall use (to support TestContext)
// or take an existing thread-local event loop if present to avoid blocking it (but don't create one)
eventLoop = (contextInterceptor as? EventLoop)?.takeIf { it.shouldBeProcessedFromContext() }
?: ThreadLocalEventLoop.currentOrNull()
newContext = GlobalScope.newCoroutineContext(context)
}
val coroutine = BlockingCoroutine<T>(newContext, currentThread, eventLoop)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine.joinBlocking()
}runBlocking是普通函數(shù),第一個(gè)參數(shù):context: CoroutineContext,協(xié)程上下文。第二個(gè)參數(shù)是函數(shù)類(lèi)型,block: suspend CoroutineScope.() -> T,函數(shù)類(lèi)型是有返回值類(lèi)型 T 的,與 runBlocking 的返回值類(lèi)型是一樣的,runBlocking 其實(shí)是可以從協(xié)程當(dāng)中返回執(zhí)行結(jié)果的。
fun testRunBlocking() {
val runBlockingResult = runBlocking {
delay(500L)
return@runBlocking "HaHa"
}
println("result:$runBlockingResult")
}
result:HaHarunBlocking特點(diǎn):
runBlocking 啟動(dòng)的協(xié)程會(huì)阻塞當(dāng)前線程的執(zhí)行。
3.async啟動(dòng)協(xié)程
使用 async{} 創(chuàng)建協(xié)程,可以通過(guò)它返回的Deferred拿到協(xié)程的執(zhí)行結(jié)果。
代碼示例
fun testAsync() {
runBlocking {
val deferred = async {
println("do async:${Thread.currentThread().name}")
delay(1000L)
return@async "do completed"
}
println("After async:${Thread.currentThread().name}")
val result = deferred.await()
println("Result is: $result")
}
}
After async:main @coroutine#1
do async:main @coroutine#2
Result is: do completedpublic fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T> {
val newContext = newCoroutineContext(context)
val coroutine = if (start.isLazy)
LazyDeferredCoroutine(newContext, block) else
DeferredCoroutine<T>(newContext, active = true)
coroutine.start(start, coroutine, block)
return coroutine
}async注意點(diǎn)
- async 啟動(dòng)協(xié)程以后,不會(huì)阻塞當(dāng)前程序的執(zhí)行流程。
- async{}的返回值,是一個(gè) Deferred 對(duì)象,它的 await() 方法,就可以拿到協(xié)程的執(zhí)行結(jié)果。
- await只是等待執(zhí)行完,并不是觸發(fā)執(zhí)行。
到此這篇關(guān)于Kotlin協(xié)程的啟動(dòng)方式介紹的文章就介紹到這了,更多相關(guān)Kotlin協(xié)程啟動(dòng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android 實(shí)現(xiàn)自定義圓形listview功能的實(shí)例代碼
這篇文章主要介紹了Android 實(shí)現(xiàn)自定義圓形listview功能的實(shí)例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
Android應(yīng)用開(kāi)發(fā)中觸摸屏手勢(shì)識(shí)別的實(shí)現(xiàn)方法解析
這篇文章主要介紹了Android應(yīng)用開(kāi)發(fā)中觸摸屏手勢(shì)識(shí)別的實(shí)現(xiàn)方法解析,深入的部分則是對(duì)左右手勢(shì)的識(shí)別給出了相關(guān)編寫(xiě)思路,需要的朋友可以參考下2016-02-02
Android TreeView實(shí)現(xiàn)帶復(fù)選框樹(shù)形組織結(jié)構(gòu)
這篇文章主要為大家詳細(xì)介紹了Android TreeView實(shí)現(xiàn)帶復(fù)選框樹(shù)形組織結(jié)構(gòu),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
Android中ArrayList和數(shù)組相互轉(zhuǎn)換
在我們?nèi)粘i_(kāi)發(fā)中難免會(huì)要將ArrayList和數(shù)組相互轉(zhuǎn)換,那么如何才能相互轉(zhuǎn)換呢?下面跟著小編一起通過(guò)這篇文章學(xué)習(xí)學(xué)習(xí)。2016-08-08
Android修改源碼解決Alertdialog觸摸對(duì)話(huà)框邊緣消失的問(wèn)題
在開(kāi)發(fā)的時(shí)候遇到一個(gè)問(wèn)題,就是一觸摸對(duì)話(huà)框邊緣外部,對(duì)話(huà)框會(huì)自動(dòng)消失。這個(gè)問(wèn)題很糾結(jié)啊,查找了一下發(fā)現(xiàn)從Android 4.0開(kāi)始,AlertDialog有了變化,就是在觸摸對(duì)話(huà)框邊緣外部,對(duì)話(huà)框會(huì)自動(dòng)消失,查了源碼,找到解決辦法如下2013-11-11
36個(gè)Android開(kāi)發(fā)常用經(jīng)典代碼大全
本篇文章主要介紹了36個(gè)Android開(kāi)發(fā)常用經(jīng)典代碼片段,都是實(shí)用的代碼段,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-11-11
Android WaveView實(shí)現(xiàn)水流波動(dòng)效果
這篇文章主要介紹了 Android自定義控件 WaveView實(shí)現(xiàn)水流波動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-03-03
RxJava2.x實(shí)現(xiàn)定時(shí)器的實(shí)例代碼
本篇文章主要介紹了RxJava2.x實(shí)現(xiàn)定時(shí)器,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
Android Build類(lèi)的詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了Android Build類(lèi)的詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,希望通過(guò)本文大家能夠理解掌握這部分內(nèi)容,需要的朋友可以參考下2017-08-08

