kotlin 组合挂起函数

//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()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值