芬兰湾的科特林学习教程之协程协同程序

  

  

协同程序翻译为协程,谷歌翻译为协同程序,一般也称为轻量级线程,但需要注意的是线程是操作系统里的定义概念,而协程是程序语言实现的一套异步处理的方法。

  

在芬兰湾的科特林文档中,协同程序定义为一个可被挂起的计算实例,下面话不多说了,来一起看看详细的介绍吧。

  

  

构建。gradle中依赖添加下面2行,注意协同程序目前仍处于实验阶段,但Kotline官方保证向前兼容。

        依赖关系{   实现“org.jetbrains.kotlinx: kotlinx-coroutines-core: 0.22.5”   实现“org.jetbrains.kotlinx: kotlinx-coroutines-android: 0.19.3”   }      

  

我们看一个简单Android示例:

  

activity_coroutine.xml         & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt; android.support.constraint。ConstraintLayout xmlns: android=" http://schemas.android.com/apk/res/android "   xmlns:应用=" http://schemas.android.com/apk/res-auto "   xmlns:工具=" http://schemas.android.com/tools "   android: layout_width=" match_parent "   android: layout_height=" match_parent "   工具:上下文=?coroutine.CoroutineActivity”比;      & lt; TextView   android: id=癅 + id/tvHello”   android: layout_width=" wrap_content "   android: layout_height=" wrap_content "/比;   & lt;/android.support.constraint.ConstraintLayout>      

CoroutineActivity.kt         类CoroutineActivity: AppCompatActivity () {   覆盖乐趣>   类CoroutineActivity: AppCompatActivity () {   lateinit var工作:工作   覆盖乐趣>   发射(UI)      

这行代码是指将协同程序指派在UI线程上运行

  

当我们运行一段cpu耗时操作时,则需要将协同程序指定在非UI线程上。

  

我们写成:

        发射(){…}      

这行代码等价于:

        发射(CommonPool) {…}      

我们分析下CommonPool的实现,发现它会根据当前cpu的核数创建一个线程池提供给协同程序使用。

        私人乐趣createPlainPool (): ExecutorService {   val threadId=AtomicInteger ()   返回Executors.newFixedThreadPool (defaultParallelism ()) {   线程(它,”CommonPool-worker - $ {threadId.incrementAndGet ()}”)。应用{isDaemon=true}   }   }      私人乐趣defaultParallelism ()=(Runtime.getRuntime () .availableProcessors () - 1) .coerceAtLeast (1)      

  

通过上面的分析,我们理解了协同程序是一个运行在线程上的可被挂起的计算单元实例,对协同程序的延迟,取消操作不会影响线程的运行,线程的状态变化对我们是透明的,我们不需要关心。

  

所以使用协同程序,可以使我们更加方便得处理异步操作,比如网络请求,数据存储等。

  

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

芬兰湾的科特林学习教程之协程协同程序