协程 - Go语言中文社区

协程


协程

1.Kotlin 中的协程是什么?

简单理解:一般程序会有一个主进程,主进程中可能含有多个线程。而协程,是线程中的,也就是说一个线程中可能包含多个协程,协程与协程之间是可以嵌套的。

image

2.有什么作用?

当线程要执行可能会阻塞的任务时,一般情况下会开启一个子线程来完成,如果阻塞任务过多,就需要开启多个子线程(线程池),协程可以帮助我们完成的是,将可能会阻塞的任务放在线程的协程中来完成,多个任务就创建多个协程。线程直接维持数据准确性需要消耗很多资源,而协程消耗的会少很多。

注:协程是可以直接运行在进程中的,不是一定要依赖于线程,只不过现在支持协程的 Kotlin Python Go 等语言都会以主线程的方式开启程序的运行。

总结:通过提升 CPU 利用率,减少线程切换进而提升程序运行效率。

3.协程的特性

  • 可控制:协程能做到可被控制的发起子任务(协程的启动和停止都由代码控制,不像 java)
  • 轻量级:协程非常小,占用资源比线程还少
  • 语法糖:使多任务或多线程切换不再使用回调语法

二、协程库

kotlinx.coroutines
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5"

1.使用 idea 创建 gradle 工程

image

2.在Kotlin中启动协程

  • runBlocking: T
    • 用于执行协程任务,通常只用于启动最外层的协程(线程到协程的调度)
  • launch: Job
    • 用于执行协程任务,返回的 Job 是一个接口引用
  • async/await: Deferred
    • 用于执行协程任务,并得到执行结果
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking

/**
 * main=runBlocking
 * 表示主线程开始后直接就开启了一个协程
 * 在协程中执行任务
 */
fun main(args: Array<String>) = runBlocking {

    val job = launch {
        repeat(10) { I ->

            println("挂起中------$I")
            //每次循环,暂停1秒
            delay(1000L)

        }
    }

    val job2 = async {
        //挂起5秒
        delay(5000L)
        //使用注解标注此处返回的是 async 的闭包
        return@async "我是 async 返回的内容"
    }

    /**
     * await 是一个阻塞式方法
     * 会将主线程停在这里
     * 当 job2 挂起5秒结束,返回内容
     * await 接受到内容,主线程才继续向下执行-->开始等待
     */
    println("job2 返回的内容:${job2.await()}")
    println("主线程开始等待-----")
    delay(3000L)
    println("主线程等待结束-----取消launch开启的协程")
    job.cancel()//协程的启动和停止都是代码可控的

    println("主线程执行完毕,即将推出-----")

}
image

三、协程的启动参数

以下是 launch 的参数列表,runBlocking、async 与 launch 参数列表是差不多的

  • context: CoroutineContext = DefaultDispatcher
    • 当前 协程 的上下文,用于在 协程 与 协程 之间参数传递
    • 可以用于声明当前 协程 在哪一个线程中声明,以及当前 协程 被中断后,在哪一个线程中恢复它
    • DefaultDispatcher 就是一个默认的调度器,当前哪个线程在运行,就直接取哪个线程
  • start: CoroutineStart = CoroutineStart.DEFAULT
    • 协程 的启动参数,表示已哪种方式启动
    • CoroutineStart.DEFAULT 默认的启动方式,表示当前线程什么时候有空,就什么时候启动
    • 可选参数:LAZY,如果没有手动调用 job 对象的 start() 或 join() 方法的话,那么该 协程 是不会被启动的
    • 可选参数:ATOMIC,将 协程 以一个原子性质的形式的启动,如果声明此参数,则协程是不可以 cancel 的
    • 可选参数:UNDISPATCHED,未定义,通常用于自定义的启动方式,如果未自定义,则与 DEFAULT 启动方式一致。
  • parent: Job? = null
    • 表示在当前 协程 闭包的外层的 job,一般情况下使用不到
  • block: suspend CoroutineScope.() -> Unit
    • 协程真正要去执行的内容

四、协程的语法糖

允许我们使用同步的代码格式,发起一次异步的网络请求

package zyf.com.kotlin_

import android.os.AsyncTask
import kotlinx.coroutines.experimental.CoroutineDispatcher
import kotlinx.coroutines.experimental.Runnable
import kotlin.coroutines.experimental.CoroutineContext

/**
 * create by zyf on 2018/9/17 下午4:58
 */
object AndroidCommonPool: CoroutineDispatcher(){
    override fun dispatch(context: CoroutineContext, block: Runnable) {
        //使用android官方提供的线程池来执行任务
        AsyncTask.THREAD_POOL_EXECUTOR.execute(block)
    }
}
package zyf.com.kotlin_

import android.widget.TextView
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import okhttp3.OkHttpClient
import okhttp3.Request

/**
 * create by zyf on 2018/9/17 下午4:46
 */
private val mOkHttpClient= OkHttpClient()
private val mRequest=Request.Builder().url("https://www.baidu.com").get().build()

fun ktGet(textView: TextView) = runBlocking{

    launch(UI) {
        //传入的AndroidCommonPool表示 async 开启的这个协程,允许在 AndroidCommonPool 提供的线程中
        textView.text = async(AndroidCommonPool) {
            mOkHttpClient.newCall(mRequest).execute().body()?.string()
        }.await()
    }


}

package zyf.com.kotlin_

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


    }

    fun java(v:View){

    }

    fun kotlin(v:View){
        ktGet(showTv)
    }
}

<?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=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/showTv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/javaBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Java获取网络数据"/>

            <Button
                android:id="@+id/kotlinBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Kotlin获取网络数据"
                android:onClick="kotlin"/>

            <Button
                android:id="@+id/cleanBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="清除"/>
        </LinearLayout>
    </ScrollView>

</android.support.constraint.ConstraintLayout>
版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/0add49034b7f
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 13:00:14
  • 阅读 ( 1242 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢