1.导入
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
2.使用
A. 开启协程的方式:GlobalScope.launch
val launch = GlobalScope.launch {
.....
}
launch接收3个参数,context: CoroutineContext
, start: CoroutineStart
以及 block: suspend CoroutineScope.() -> Unit
第三个参数:就是你需要执行的代码,这个不用讲;
第一个参数:(我们可传入以下4种)
Dispatchers.Default
默认线程池,协程体中的代码将被分配到 线程 中执行;Dispatchers.IO
线程池,协程体中的代码将被分配到 线程 中执行;Dispatchers.Main
主线程,协程体中的的代码将在 主线程 中执行;Dispatchers.Unconfined
将在调用协程时所处的线程中执行协程体中的代码;
如:在主线程中调用协程,则协程体中的代码也将运行在主线程中;
第二个参数:
start = CoroutineStart.DEFAULT
作用:立即执行协程体 默认值
println("协程 主线程:${
Thread.currentThread()}")
val launch = GlobalScope.launch {
println("协程1:${
Thread.currentThread()}")
println("协程1 主线程?:${
Looper.getMainLooper() == Looper.myLooper()}")
val deferredA: Deferred<Int> = async(Dispatchers.Default) {
println("协程A:${
Thread.currentThread()}")
println("协程A 主线程?:${
Looper.getMainLooper() == Looper.myLooper()}")
delay(2000)
var a = 0
for (i in 0..100) a += i
a
}
val deferredB = async(Dispatchers.Default) {
println("协程B:${
Thread.currentThread()}")
println("协程B 主线程?:${
Looper.getMainLooper() == Looper.myLooper()}")
delay(4000)
var b = 1
for (i in 0..50) b += i
b
}
println("协程:输出第一句")
val i = deferredA.await() + deferredB.await()
println("协程:$i")
println("协程:输出第二句")
}
launch.cancel()//直接取消
打印日志:
I/System.out: 协程 主线程:true
I/System.out: 协程1:Thread[DefaultDispatcher-worker-1,5,main]
I/System.out: 协程1 主线程?:false
I/System.out: 协程:输出第一句
结论:
调用launch.cancel()
后,协程体会被直接停止运行;
注释掉launch.cancel()
后,打印日志:
I/System.out: 协程 主线程:true
I/System.out: 协程1:Thread[DefaultDispatcher-worker-2,5,main]
I/System.out: 协程1 主线程?:false
I/System.out: 协程A:Thread[DefaultDispatcher-worker-1,5,main]
I/System.out: 协程A 主线程?:false
I/System.out: 协程:输出第一句
I/System.out: 协程B:Thread[DefaultDispatcher-worker-3,5,main]
I/System.out: 协程B 主线程?:false
I/System.out: 协程:6326
I/System.out: 协程:输出第二句
结论:
正常执行,直到协程体执行结束;
start = CoroutineStart.ATOMIC
作用:立即执行协程体,但在开始运行之前无法取消
println("协程 主线程: