社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
简单理解:一般程序会有一个主进程,主进程中可能含有多个线程。而协程,是线程中的,也就是说一个线程中可能包含多个协程,协程与协程之间是可以嵌套的。
当线程要执行可能会阻塞的任务时,一般情况下会开启一个子线程来完成,如果阻塞任务过多,就需要开启多个子线程(线程池),协程可以帮助我们完成的是,将可能会阻塞的任务放在线程的协程中来完成,多个任务就创建多个协程。线程直接维持数据准确性需要消耗很多资源,而协程消耗的会少很多。
注:协程是可以直接运行在进程中的,不是一定要依赖于线程,只不过现在支持协程的 Kotlin
Python
Go
等语言都会以主线程的方式开启程序的运行。
总结:通过提升 CPU 利用率,减少线程切换进而提升程序运行效率。
kotlinx.coroutines
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5"
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("主线程执行完毕,即将推出-----")
}
以下是 launch 的参数列表,runBlocking、async 与 launch 参数列表是差不多的
允许我们使用同步的代码格式,发起一次异步的网络请求
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>
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!