Kotlin學(xué)習(xí)教程之協(xié)程Coroutine
定義
Coroutine翻譯為協(xié)程,Google翻譯為協(xié)同程序,一般也稱為輕量級(jí)線程,但需要注意的是線程是操作系統(tǒng)里的定義概念,而協(xié)程是程序語(yǔ)言實(shí)現(xiàn)的一套異步處理的方法。
在Kotlin文檔中,Coroutine定義為一個(gè)可被掛起的計(jì)算實(shí)例,下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。
配置
build.gradle中dependencies 添加下面2行,注意coroutine目前仍處于experiment階段,但Kotline官方保證向前兼容。
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.19.3"
}
實(shí)例
我們看一個(gè)簡(jiǎn)單Android示例:
activity_coroutine.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".coroutine.CoroutineActivity"> <TextView android:id="@+id/tvHello" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.constraint.ConstraintLayout>
CoroutineActivity.kt
class CoroutineActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_coroutine)
setup()
}
fun setup() {
launch(UI) { // launch coroutine in UI context
for (i in 10 downTo 1) { // countdown from 10 to 1
tvHello.text = "Countdown $i ..." // update text
delay(1000) // wait half a second
}
tvHello.text = "Done!"
}
}
}
運(yùn)行程序 tvHello從10倒計(jì)時(shí)顯示到1,最后顯示"Done!"
代碼分析:
我們重點(diǎn)分析setup()函數(shù)
- launch(UI) {...} -----在UIcontext下啟動(dòng)coroutine
- delay(1000) ----將當(dāng)前coroutine掛起1秒
看到這里你可能會(huì)疑惑,Android開(kāi)發(fā)中不是禁止在主線程下做延遲或者阻塞操作嗎?
我們回顧下Coroutine的定義:一個(gè)可被掛起的計(jì)算實(shí)例。
Coroutine不是線程,所以掛起Coroutine不會(huì)影響當(dāng)前線程的運(yùn)行。
取消Coroutine運(yùn)行
我們修改下上面的代碼:
class CoroutineActivity : AppCompatActivity() {
lateinit var job:Job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_coroutine)
setup()
}
fun setup() {
job = launch(CommonPool) { // launch coroutine in UI context
for (i in 10 downTo 1) { // countdown from 10 to 1
tvHello.text = "Countdown $i ..." // update text
delay(1000) // wait half a second
}
tvHello.text = "Done!"
}
}
override fun onPause() {
super.onPause()
job.cancel()
}
}
重點(diǎn)是 launch(UI)返回給一個(gè)job實(shí)例,通過(guò)job.cancel()取消coroutine。
Coroutine和thread關(guān)系
我們?cè)俜治鱿?/p>
launch(UI)
這行代碼是指將coroutine指派在UI線程上運(yùn)行
當(dāng)我們運(yùn)行一段cpu耗時(shí)操作時(shí),則需要將coroutine指定在非UI線程上。
我們寫(xiě)成:
launch(){...}
這行代碼等價(jià)于:
launch(CommonPool){...}
我們分析下CommonPool的實(shí)現(xiàn),發(fā)現(xiàn)它會(huì)根據(jù)當(dāng)前cpu的核數(shù)創(chuàng)建一個(gè)線程池提供給Coroutine使用。
private fun createPlainPool(): ExecutorService {
val threadId = AtomicInteger()
return Executors.newFixedThreadPool(defaultParallelism()) {
Thread(it, "CommonPool-worker-${threadId.incrementAndGet()}").apply { isDaemon = true }
}
}
private fun defaultParallelism() = (Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1)
總結(jié):
通過(guò)上面的分析,我們理解了Coroutine是一個(gè)運(yùn)行在線程上的可被掛起的計(jì)算單元實(shí)例,對(duì)Coroutine的delay,cancel操作不會(huì)影響線程的運(yùn)行,線程的狀態(tài)變化對(duì)我們是透明的,我們不需要關(guān)心。
所以使用Coroutine,可以使我們更加方便得處理異步操作,比如網(wǎng)絡(luò)請(qǐng)求,數(shù)據(jù)存儲(chǔ)等。
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- Kotlin-Coroutines中的async與await異步協(xié)程管理
- Kotlin?LinearLayout與RelativeLayout布局使用詳解
- Kotlin FrameLayout與ViewPager2控件實(shí)現(xiàn)滾動(dòng)廣告欄方法
- kotlin協(xié)程之coroutineScope函數(shù)使用詳解
- Kotlin協(xié)程啟動(dòng)createCoroutine及創(chuàng)建startCoroutine原理
- Android結(jié)合kotlin使用coroutine的方法實(shí)例
- kotlin中泛型中in和out的區(qū)別解析
相關(guān)文章
通過(guò)實(shí)例解析android Activity啟動(dòng)過(guò)程
這篇文章主要介紹了通過(guò)實(shí)例解析android Activity啟動(dòng)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Android 8.0系統(tǒng)中應(yīng)用圖標(biāo)的適配微技巧
這篇文章主要介紹了Android 8.0系統(tǒng)中應(yīng)用圖標(biāo)的適配微技巧 ,需要的朋友可以參考下2018-04-04
基于android startActivityForResult的學(xué)習(xí)心得總結(jié)
本篇文章是對(duì)android中的startActivityForResult進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android APT 實(shí)現(xiàn)控件注入框架SqInject的示例
這篇文章主要介紹了Android APT 實(shí)現(xiàn)控件注入框架SqInject的示例,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03
Flutter實(shí)現(xiàn)紅包動(dòng)畫(huà)效果的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Flutter實(shí)現(xiàn)紅包的動(dòng)畫(huà)效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下2023-06-06

