package com.tiger.mykotlinapp.scope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking fun main():Unit = runBlocking { val d = async(start = CoroutineStart.LAZY){ test() } println("hello") println("hello") println("hello") println("hello") println("hello") println("hello") println("hello") println(d.await())//代表开启线程执行, 拿到返回值 } suspend fun test():Int{ println("执行中") delay(1000) return 100 }
package com.tiger.mykotlinapp.scope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.select fun main():Unit = runBlocking { val d = async(start = CoroutineStart.LAZY){ test1("1") } val c = async(start = CoroutineStart.LAZY){ delay(2000) test1("2") } println(select{ //阻塞主线程把协程等待结束再继续执行 谁先执行完毕,就退出返回先结束的那个返回值 c.onAwait.invoke { it } d.onAwait.invoke { it } }) println("end") // println(d.await())//代表开启线程执行, 拿到返回值 } suspend fun test1(a:String):String{ println("执行中$a") delay(1000) return a }
package com.tiger.mykotlinapp.scope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.select fun main():Unit = runBlocking { val d = async(start = CoroutineStart.LAZY){ test3("1") } val c = async(start = CoroutineStart.LAZY){ delay(2000) test3("2") } println(select{ //阻塞主线程把协程等待结束再继续执行 谁先执行完毕,就退出返回先结束的那个返回值 c.onAwait.invoke { it } d.onAwait.invoke { it } }) println("end") // println(d.await())//代表开启线程执行, 拿到返回值 } suspend fun test3(a:String):String{ println("执行中$a") delay(1000) return a }
这个是立刻获取协程异步执行的值
如果还没执行完毕就抛异常