Kotlin學(xué)習(xí)教程之協(xié)程Coroutine
定義
Coroutine翻譯為協(xié)程,Google翻譯為協(xié)同程序,一般也稱為輕量級(jí)線程,但需要注意的是線程是操作系統(tǒng)里的定義概念,而協(xié)程是程序語言實(shí)現(xiàn)的一套異步處理的方法。
在Kotlin文檔中,Coroutine定義為一個(gè)可被掛起的計(jì)算實(shí)例,下面話不多說了,來一起看看詳細(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è)簡單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開發(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í)例,通過job.cancel()取消coroutine。
Coroutine和thread關(guān)系
我們再分析下
launch(UI)
這行代碼是指將coroutine指派在UI線程上運(yùn)行
當(dāng)我們運(yùn)行一段cpu耗時(shí)操作時(shí),則需要將coroutine指定在非UI線程上。
我們寫成:
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é):
通過上面的分析,我們理解了Coroutine是一個(gè)運(yùn)行在線程上的可被掛起的計(jì)算單元實(shí)例,對(duì)Coroutine的delay,cancel操作不會(huì)影響線程的運(yùn)行,線程的狀態(tài)變化對(duì)我們是透明的,我們不需要關(guān)心。
所以使用Coroutine,可以使我們更加方便得處理異步操作,比如網(wǎng)絡(luò)請求,數(shù)據(jù)存儲(chǔ)等。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(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)文章
Android編程中FileOutputStream與openFileOutput()的區(qū)別分析
這篇文章主要介紹了Android編程中FileOutputStream與openFileOutput()的區(qū)別,結(jié)合實(shí)例形式分析了FileOutputStream與openFileOutput()的功能,使用技巧與用法區(qū)別,需要的朋友可以參考下2016-02-02最常見的猜拳小游戲Android代碼實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了最常見的猜拳小游戲Android代碼實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08Android中ViewPager實(shí)現(xiàn)滑動(dòng)條及與Fragment結(jié)合的實(shí)例教程
ViewPager類主要被用來實(shí)現(xiàn)可滑動(dòng)的視圖功能,這里我們就來共同學(xué)習(xí)Android中ViewPager實(shí)現(xiàn)滑動(dòng)條及與Fragment結(jié)合的實(shí)例教程,需要的朋友可以參考下2016-06-06簡單實(shí)現(xiàn)Android計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了自己動(dòng)手實(shí)現(xiàn)的Android計(jì)算器功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01Android studio配置lambda表達(dá)式教程
Java 8的一個(gè)大亮點(diǎn)是引入Lambda表達(dá)式,使用它設(shè)計(jì)的代碼會(huì)更加簡潔。接下來通過本文給大家介紹Android studio配置lambda表達(dá)式教程,需要的朋友參考下吧2017-05-05android實(shí)現(xiàn)自動(dòng)關(guān)機(jī)的具體方法
android實(shí)現(xiàn)自動(dòng)關(guān)機(jī)的具體方法,需要的朋友可以參考一下2013-06-06