一、开启协程的方式
- 使用 runBlocking 顶层函数。它会 在协程作用域内的所有代码和子协程没有全部执行完成之前 一直阻塞当前线程。一般在测试环境中使用。
runBlocking {
}
- 使用 GlobalScope 单例对象。也是顶层协程。不推荐使用。
GlobalScope.launch {
}
- 创建 CoroutineScope 对象。CoroutineScope()是一个函数,会返回一个CoroutineScope对象。之后调用它的launch函数就可以创建一个协程。
CoroutineScope(Dispatchers.XX).launch {
}
- launch,会在协程域中再开子协程。
runBlocking {
launch { }
}
- async方式,会在协程域中再开子协程。返回值是一个实现了Job接口的Dererred对象。
runBlocking {
async {
}
}
asnyc会返回一个Dererred对象。如果想要获得async函数代码块的运行结果,可以调用Dererred的await()方法。
runBlocking {
val deferred = async {
1+1
}
println(deferred.await())
}
await()方法会阻塞当前协程,直到获取到async函数的结果。
二、Dispatchers指定线程
- Dispatchers.Main:Android 中的主线程
- Dispatchers.IO:针对磁盘和网络 IO 进行了优化,适合 IO 密集型的任务,比如:读写文件,操作数据库以及网络请求
- Dispatchers.Default:适合 CPU 密集型的任务,比如计算
- Dispatchers.Unconfined:不推荐使用
runBlocking {
withContext(Dispatchers.Main){
}
withContext(Dispatchers.IO){
}
withContext(Dispatchers.Default){
}
}
三、suspend 关键字修饰的函数
表示该函数需要在协程中调用。
private suspend fun test(string:String) {
println(string)
}
private suspend fun test(string:String) = withContext(Dispatchers.IO){
}
private suspend fun test(string:String) :String = withContext(Dispatchers.IO){
"xxx"
}
协程代码块中代码运行到suspend函数时,会暂时不再执行剩余的协程代码,而是先执行完suspend函数再继续往下执行。
fun main(arg: Array<String>) {
CoroutineScope(Dispatchers.Default).launch {
println("1")
test() // 运行到suspend函数,会执行完suspend函数之后再往下执行
println("2")
}
Thread.sleep(6000)
println("end")
}
suspend fun test() {
delay(3000)
println("test")
}
运行结果
1
test
2
end
四、子协程launch代码块
子协程launch代码块不会影响后面代码的运行(因为子协程本来就是新的协程,和原来的代码块分开各跑各的)。
fun main(arg: Array<String>) {
CoroutineScope(Dispatchers.Default).launch {
launch { // 新的子协程,不影响后面代码的运行
delay(3000)
println("0")
}
test()
println("1")
}
Thread.sleep(6000)
println("end")
}
suspend fun test() {
delay(1000)
println("test")
}
运行结果
test
1
0
end
六、coroutineScope函数和CoroutineScope函数的区别。
- coroutineScope函数是一个由suspend修饰的挂起函数,需要在协程作用域中被调用。也可以在其它挂起函数中调用。coroutineScope{}中的代码执行完之前,一直阻塞外部协程(因为它是挂起函数)。
fun main() {
runBlocking { // runBlocking阻塞了外部线程
coroutineScope{
// coroutineScope阻塞了runBlocking协程
launch {
for (i in 1..10) {
println(i)
delay(1000)
}
}
}
println("runBlocking last line.")
}
println("main finished.")
}
运行结果:
1
2
3
4
5
6
7
8
9
10
runBlocking last line.
main finished.
- CoroutineScope()是一个函数,会返回一个CoroutineScope对象。之后调用它的launch函数就可以创建一个协程。不会阻塞外部线程、协程。
fun main() {
runBlocking {
CoroutineScope(Dispatchers.Default).launch{
for (i in 1..10) {
println(i)
delay(1000)
}
}
println("runBlocking last line.")
}
println("main finished.")
}
运行结果:
既没有阻塞外部线程也没有阻塞外部协程。
runBlocking last line.
1
main finished.