1、协程是kotlin的线程框架
2、协程最大的特点就是:它可以很方便的在同一个代码块中,多次切换线程,然后再自动切回去
3、协程的挂起,就是把线程切走,标识是supend关键词和withContext方法
4、协程的非阻塞,也是再说把线程切走,阻塞这个概念是再单一线程中的概念,当它切换了线程,也就没有阻塞这么一说了。
5、协程是基于线程的上层框架
package com.luoyang.androidfunDemo.launch
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.luoyang.androidfunDemo.R
import kotlinx.coroutines.*
class LaunchTestActivity : AppCompatActivity() {
private lateinit var mLaunchText: TextView
companion object {
const val TAG = "LaunchTestActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launch_test)
initView()
// testBlockLaunch()
testGlobalLaunch()
}
private fun initView() {
mLaunchText = findViewById(R.id.launch_text)
}
private fun testGlobalLaunch() {
val buffer = StringBuffer()
GlobalScope.launch(Dispatchers.Main) {//全局作用域用于启动在整个应用程序生命周期内运行且不会过早取消的顶级协程
launch() {//lauch也是协程构建器,启动了一个新协程,我们称它为coroutine#1, 它是coroutine#main的子协程
// launch(Dispatchers.IO) {//lauch也是协程构建器,启动了一个新协程,我们称它为coroutine#1, 它是coroutine#main的子协程
buffer.append("GlobalLaunch1 started n")
Log.d(TAG, "GlobalLaunch1 started")//打印信息
delay(3000)//暂停3000ms,也说是挂起
buffer.append("GlobalLaunch1 ended n")
Log.d(TAG, "GlobalLaunch1 ended")//打印信息
mLaunchText.text = buffer.toString()
}
// launch() {//同上,只是顺序在coroutine#1的后面 我们称其coroutine#2
launch() {//同上,只是顺序在coroutine#1的后面 我们称其coroutine#2
buffer.append("GlobalLaunch2 started n")
Log.d(TAG, "GlobalLaunch2 started")//打印信息
delay(2000)//暂停2000ms,也说是挂起
buffer.append("GlobalLaunch2 ended n")
Log.d(TAG, "GlobalLaunch2 ended")//打印信息
mLaunchText.text = buffer.toString()
}
buffer.append("Global go go n")
Log.d(TAG, "Global go go")//打印信息
mLaunchText.text = buffer.toString()
}
}
private fun testBlockLaunch() {
val buffer = StringBuffer()
runBlocking() {//runBlocking是一个协程构建器,它会启动一个阻塞线程的协程,但也是协程,coroutine#main
launch() {//lauch也是协程构建器,启动了一个新协程,我们称它为coroutine#1, 它是coroutine#main的子协程
// launch(Dispatchers.IO) {//lauch也是协程构建器,启动了一个新协程,我们称它为coroutine#1, 它是coroutine#main的子协程
buffer.append("BlockLaunch1 started n")
Log.d(TAG, "BlockLaunch1 started")//打印信息
delay(3000)//暂停3000ms,也说是挂起
buffer.append("BlockLaunch1 ended n")
Log.d(TAG, "BlockLaunch1 ended")//打印信息
}
launch {//同上,只是顺序在coroutine#1的后面 我们称其coroutine#2
buffer.append("BlockLaunch2 started n")
Log.d(TAG, "BlockLaunch2 started")//打印信息
delay(2000)//暂停2000ms,也说是挂起
buffer.append("BlockLaunch2 ended n")
Log.d(TAG, "BlockLaunch2 ended")//打印信息
}
buffer.append("Block go go n")
Log.d(TAG, "Block go go")//打印信息
}
mLaunchText.text = buffer.toString()
}
}
参考视频
携程是kotliin线程框架
携程挂起,把线程切走,标识是supend关键词和withContext方法
非阻塞,把线程切走,协程是基于线程的上层框架
参考文档
kotlin协程实例分析



