一.协程的启动
1.协程构建器
launch与async构建器都用来启动新协程:
launch,返回一个Job并且不附带任何结果值。
async,返回一个Deferred,Deferred也是一个job,可以使用await在一个延期的值上得到它的最终结果。
fun main() {
testCoroutine();
}
// runBlocking 主协程 他会等子协程任务执行完再关闭,在此之前都是堵塞状态
fun testCoroutine()= runBlocking {
//async的await函数会延时返回一个结果值,launch不能
val job = launch {
delay(2000)
println( "launch finished")
}
val job1 = async {
delay(2000)
println( "async finished")
"async result"
}
println(job1.await())
}
打印结果:
launch finished
async finished
async result
2.launch与async的顺序执行
我们经常会碰到这样一个情况,在调取一个接口获取信息后再调取其他接口,这样按顺序调取。
1.launch
fun main() {
testCoroutine1();
}
//runBlocking 主协程 他会等子协程任务执行完再关闭,在此之前都是堵塞状态
fun testCoroutine1()= runBlocking {
//都是异步任务
val launch = launch {
delay(100)
println("One")
}
//join是一个挂起函数 他会暂停协程直到所有的任务完成
launch.join()
val launch1 = launch {
delay(100)
println("Two")
}
val launch2 = launch {
delay(100)
println("Three")
}
}
打印结果:
One
Two
Three
2.async
fun main() {
testCoroutine1();
}
//runBlocking 主协程 他会等子协程任务执行完再关闭,在此之前都是堵塞状态
fun testCoroutine1()= runBlocking {
val async = async {
delay(100)
println("One")
}
async.await()
val async1 = async {
delay(100)
println("Two")
}
val async2 = async {
delay(100)
println("Three")
}
}
打印结果:
One
Two
Three
3.async结构化并发
fun main() {
TestSync()
}
//runBlocking 主协程 他会等子协程任务执行完再关闭,在此之前都是堵塞状态
fun TestSync()= runBlocking {
val time = measureTimeMillis {
//这样可以同时开始两个子协程执行并发任务
val doOne = async {doOne() }
val doTwo = async {doTwo() }
//这里是调用的同步方法等全部执行完后进行运算
print("The result:${doOne.await() + doTwo.await()} \