//1.按顺序执行 fun main1() = runBlocking<Unit> { val time = measureTimeMillis { //计算时间 var one = doOne() var two = doTwo() println("onetwo Time is ${one+two}")//相加 } println("Time is ${time}") } suspend fun doOne(): Int { delay(1000)//延迟1秒 return 1 } suspend fun doTwo(): Int { delay(2000)//延迟2秒 return 2 } //2.并发执行 async fun mainAsync() = runBlocking<Unit> { val time = measureTimeMillis { //计算时间 var one = async { doOne()}// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象 var two = async { doTwo()}// println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值 } println("Time is ${time}") } //3.惰性启动 fun mainLazy() = runBlocking<Unit> { val time = measureTimeMillis { //计算时间 var one = async(start = CoroutineStart.LAZY) { doOne()}// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象 var two = async (start = CoroutineStart.LAZY){ doTwo()} one.start()//开始执行协程 ,注意如果 先调用await() 会启动协程并等待其完成 two.start() println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值 } println("Time is ${time}") } //4.并发结构 fun main_async1() = runBlocking<Unit> { val time = measureTimeMillis { //计算时间 doThings() } println("Time is ${time}") } suspend fun doThings():Int=coroutineScope { var one = async() { doOnes() }// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象 var two = async() { doTwos() } println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值 one.await() + two.await()//one.await()获取返回的值 } suspend fun doOnes(): Int { delay(1000) // pretend we are doing something useful here return 1 } suspend fun doTwos(): Int { delay(2000) // pretend we are doing something useful here return 2 } fun main_async2() = runBlocking<Unit> { try { currentSum() }catch (e:Exception){ println("main_async2 Exception..") } } suspend fun currentSum():Int= coroutineScope { val one=async<Int> { try { delay(1000) }finally { println("one finally") } 1 } val two=async<Int> { delay(2000) println("two exception..") throw ArithmeticException()//先子类协程抛异常 然后父类协程再抛异常 } one.await()+two.await() }
kotlin 组合挂起函数
最新推荐文章于 2025-03-06 10:05:03 发布