欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Kotlin-Coroutines中的async與await異步協(xié)程管理

 更新時間:2023年10月17日 12:01:25   作者:ZoranLee  
這篇文章主要為大家介紹了Kotlin-Coroutines中的async與await異步協(xié)程管理,提升程序性能解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

Coroutines

官網(wǎng)說明

什么是協(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é)程并阻塞調(diào)用它的線程
  • launch:Job 啟動一個協(xié)程但不會阻塞調(diào)用線程(CoroutineScope作用域內(nèi)調(diào)用)
  • async:Deferred<T> 啟動一個協(xié)程但不會阻塞調(diào)用線程(CoroutineScope作用域內(nèi)調(diào)用)

協(xié)程作用域(CoroutineScope)

GlobalScope 全局頂級協(xié)程 (現(xiàn)在 GlobalScope 類已被 @DelicateCoroutinesApi 注解所標(biāo)記) 全局范圍
啟動一個協(xié)程:

CoroutineScope https://developer.android.com/topic/libraries/architecture/coroutines

MainScope 主線程的作用域,全局范圍

lifecycleScope 生命周期范圍,用于activity等有生命周期的組件,DESTROYED結(jié)束。

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)
        }
    }
}
 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í)行任務(wù)的組合
  • 所有任務(wù)的工作都可以以某種任意順序交錯
  • 這些任務(wù)不一定必須同時執(zhí)行
    它的主要目標(biāo)是結(jié)構(gòu),而不是并行性

并行

  • 同時執(zhí)行多個事物
  • 與多個任務(wù)的執(zhí)行有關(guān)

并發(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
}

 結(jié)果

one
two
The answer is 1 2
Completed in 1020 ms

并行

  • GlobalScope
  • 指定協(xié)同調(diào)度程序
  • 暫停阻塞
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é)程管理的詳細內(nèi)容,更多關(guān)于Kotlin Coroutines異步協(xié)程的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論