Kotlin-Coroutines中的async與await異步協(xié)程管理
Coroutines
什么是協(xié)程?(摘自官網(wǎng))
- Asynchronous or non-blocking programming is an important part of the development landscape. 用于異步或非阻塞 編程。
簡單概括
- 同步的方式去編寫異步執(zhí)行的代碼
- 協(xié)程依賴于線程
- 協(xié)程掛起時不需要阻塞線程,幾乎是無代價的.
- 一個線程中可以創(chuàng)建N個協(xié)程
協(xié)程的創(chuàng)建/啟動
- runBlocking 啟動一個新的協(xié)程并阻塞調用它的線程
- launch:Job 啟動一個協(xié)程但不會阻塞調用線程(CoroutineScope作用域內調用)
- async:Deferred<T> 啟動一個協(xié)程但不會阻塞調用線程(CoroutineScope作用域內調用)
協(xié)程作用域(CoroutineScope)
GlobalScope 全局頂級協(xié)程 (現(xiàn)在 GlobalScope 類已被 @DelicateCoroutinesApi 注解所標記) 全局范圍
啟動一個協(xié)程:

CoroutineScope https://developer.android.com/topic/libraries/architecture/coroutines
MainScope 主線程的作用域,全局范圍
lifecycleScope 生命周期范圍,用于activity等有生命周期的組件,DESTROYED結束。
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val params = TextViewCompat.getTextMetricsParams(textView)
val precomputedText = withContext(Dispatchers.Default) {
PrecomputedTextCompat.create(longTextContent, params)
}
TextViewCompat.setPrecomputedText(textView, precomputedText)
}
}
}
- viewModelScope:viewModel范圍,ViewModel被回收時結束
class MyViewModel: ViewModel() {
init {
viewModelScope.launch {
// Coroutine that will be canceled when the ViewModel is cleared.
}
}
}
val user: LiveData<User> = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
異步、并發(fā)、并行
異步
- 是一種編程模型
- 獨立于主程序流事件的發(fā)生
- 異步啟動的操作,不會立即阻塞程序,并同時發(fā)生
異步是實現(xiàn)非阻塞和并發(fā)編程的編程模型
并發(fā)
- 獨立執(zhí)行任務的組合
- 所有任務的工作都可以以某種任意順序交錯
- 這些任務不一定必須同時執(zhí)行
它的主要目標是結構,而不是并行性
并行
- 同時執(zhí)行多個事物
- 與多個任務的執(zhí)行有關
并發(fā)就是一次處理很多事情,并行就是一次做很多事情
協(xié)程中的并發(fā)和并行
- 掛起而非阻塞 ,一個并發(fā)的例子
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main(args: Array<String>) =
runBlocking {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await()} ${two.await()}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulTwo() :Int{
delay(1000L)
println("two")
return 2
}
suspend fun doSomethingUsefulOne():Int {
delay(1000L)
println("one")
return 1
}結果
one
two
The answer is 1 2
Completed in 1020 ms
并行
- GlobalScope
- 指定協(xié)同調度程序
- 暫停阻塞
suspend fun doSomethingUsefulOne(): BigInteger = withContext(Dispatchers.Default) {
measureTimedValue {
println("in doSomethingUsefulOne")
BigInteger(1500, Random()).nextProbablePrime()
}
}.also {
println("Prime calculation took ${it.duration} ms")
}.value以上就是Kotlin-Coroutines中的async與await異步協(xié)程管理的詳細內容,更多關于Kotlin Coroutines異步協(xié)程的資料請關注腳本之家其它相關文章!
相關文章
Springboot整合實現(xiàn)郵件發(fā)送的原理詳解
SpringBoot集成郵件服務非常簡單,通過簡單的學習即可快速掌握郵件業(yè)務類的核心邏輯和企業(yè)郵件的日常服務,本文給大家分享Springboot整合實現(xiàn)郵件發(fā)送的原理,一起看看吧2021-06-06
SpringBoot2 集成log4j2日志框架的實現(xiàn)
這篇文章主要介紹了SpringBoot2 集成log4j2日志框架的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10
SpringCloud @RefreshScope注解源碼層面深入分析
@RefreshScope注解能幫助我們做局部的參數(shù)刷新,但侵入性較強,需要開發(fā)階段提前預知可能的刷新點,并且該注解底層是依賴于cglib進行代理的,所以不要掉入cglib的坑,出現(xiàn)刷了也不更新情況2023-04-04
SpringMVC + servlet3.0 文件上傳的配置和實現(xiàn)代碼
本篇文章主要介紹了SpringMVC + servlet3.0 文件上傳的配置和實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04
mybatis中BigDecimal中的0存為null的坑及解決
在使用MyBatis進行數(shù)據(jù)庫操作時,若Java中屬性類型為BigDecimal且值為0,插入數(shù)據(jù)庫時可能會變?yōu)閚ull,而不是0,這個問題可能是由于MyBatis在處理BigDecimal類型時的弱類型判斷導致的,當BigDecimal變量與空字符串進行比較時,MyBatis可能將其視為null2024-10-10
Mybatisplus實現(xiàn)JSON處理器的示例代碼
Mybatisplusjson是基于Mybatisplus開發(fā)的一個json工具庫,本文主要介紹了Mybatisplus實現(xiàn)JSON處理器的示例代碼,具有一定的參考價值,感興趣的可以了解一下2024-03-03
logback中顯示mybatis查詢日志文件并寫入的方法示例
這篇文章主要為大家介紹了logback中顯示mybatis查詢日志文件并寫入的方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03

