Kotlin學(xué)習(xí)教程之協(xié)程Coroutine
定義
Coroutine翻譯為協(xié)程,Google翻譯為協(xié)同程序,一般也稱為輕量級線程,但需要注意的是線程是操作系統(tǒng)里的定義概念,而協(xié)程是程序語言實現(xiàn)的一套異步處理的方法。
在Kotlin文檔中,Coroutine定義為一個可被掛起的計算實例,下面話不多說了,來一起看看詳細(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"
}
實例
我們看一個簡單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!"
}
}
}
運行程序 tvHello從10倒計時顯示到1,最后顯示"Done!"
代碼分析:
我們重點分析setup()函數(shù)
- launch(UI) {...} -----在UIcontext下啟動coroutine
- delay(1000) ----將當(dāng)前coroutine掛起1秒
看到這里你可能會疑惑,Android開發(fā)中不是禁止在主線程下做延遲或者阻塞操作嗎?
我們回顧下Coroutine的定義:一個可被掛起的計算實例。
Coroutine不是線程,所以掛起Coroutine不會影響當(dāng)前線程的運行。
取消Coroutine運行
我們修改下上面的代碼:
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()
}
}
重點是 launch(UI)返回給一個job實例,通過job.cancel()取消coroutine。
Coroutine和thread關(guān)系
我們再分析下
launch(UI)
這行代碼是指將coroutine指派在UI線程上運行
當(dāng)我們運行一段cpu耗時操作時,則需要將coroutine指定在非UI線程上。
我們寫成:
launch(){...}
這行代碼等價于:
launch(CommonPool){...}
我們分析下CommonPool的實現(xiàn),發(fā)現(xiàn)它會根據(jù)當(dāng)前cpu的核數(shù)創(chuàng)建一個線程池提供給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é):
通過上面的分析,我們理解了Coroutine是一個運行在線程上的可被掛起的計算單元實例,對Coroutine的delay,cancel操作不會影響線程的運行,線程的狀態(tài)變化對我們是透明的,我們不需要關(guān)心。
所以使用Coroutine,可以使我們更加方便得處理異步操作,比如網(wǎng)絡(luò)請求,數(shù)據(jù)存儲等。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
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é)
本篇文章是對android中的startActivityForResult進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android APT 實現(xiàn)控件注入框架SqInject的示例
這篇文章主要介紹了Android APT 實現(xiàn)控件注入框架SqInject的示例,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03

