kotlin协程

携程作用域

1
2
3
4
5
6
7
8
9
10
11
12
fun main() {
GlobalScope.launch {
  println("scope start ")
delay(5000)
println("scope end ")
}
println("bey ")
}

运行结果:
bey
Process finished with exit code 0

GlobalScope.launch会创建一个全局作用域的后台守护协程,它并不会阻塞当前线程。
也就是说,在程序执行完毕,协程就消失了。
如果我们想等待协程执行完毕再去关闭程序的话,可以通过获取GlobalScope.launch 返回值去调用join函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
suspend fun main() {
var job = GlobalScope.launch {
println("scope start ")
delay(5000)
println("scope end ")
}
job.join()
println("bey ")
}
运行结果:
scope start
//停顿了5s
scope end
bey

以上等同于 runBlocking

1
2
3
4
5
6
7
8
fun main() {
runBlocking {
println("block start ")
delay(5000)
println("block end ")
}
println("bey ")
}

等同于 coroutineScope创建

1
2
3
4
5
6
7
8
suspend fun main() {
var job = coroutineScope {
println("coroutineScope start ")
delay(5000)
println("coroutineScope end ")
}
println("bey")
}

等同于 withContext

1
2
3
4
5
6
7
8
suspend fun main() {
var job = withContext(Dispatchers.IO) {
println("coroutineScope start ")
delay(5000)
println("coroutineScope end ")
}
println("bey")
}

协程异步编程

新建挂起函数

1
2
3
4
5
6
7
8
9
10
11
suspend fun getMessageFromNet(requestName: String , times: Int) : String {
println("request: $requestName start ----- ")

delay(3000)
withContext(Dispatchers.IO) {
println(" net "+ Thread.currentThread().name)
(1..times).forEach {
}
}
return "result for request $requestName"
}

同步调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fun main()  = runBlocking { Dispatchers.Main
var result3 = getMessageFromNet("async1" , 100000)
var result4 = getMessageFromNet("async2" , 800000)

println("merge result ${result3.toString()} , ${result4.toString()}")
}
运行结果:
request: async1 start -----
net DefaultDispatcher-worker-1
request: async2 start -----
net DefaultDispatcher-worker-1
merge result result for request async1 , result for request async2

在第一个getMessageFromNet函数返回结果以后才发起第二次调用。

异步调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fun main()  = runBlocking { Dispatchers.Main

var result3 = async { getMessageFromNet("async1" , 100000) }
var result4 = async { getMessageFromNet("async2" , 800000) }

val await = result3.await()
val await1 = result4.await()

println("merge result ${await.toString()} , ${await1.toString()}")
}
运行结果:
request: async1 start -----
request: async2 start -----
net DefaultDispatcher-worker-1
net DefaultDispatcher-worker-2
merge result result for request async1 , result for request async2

getMessageFromNet的第二次调用不必等待第一次的结果。