Kotlin Async

package com.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.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<String> {
        //阻塞主线程把协程等待结束再继续执行 谁先执行完毕,就退出返回先结束的那个返回值

        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.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<String> {
        //阻塞主线程把协程等待结束再继续执行 谁先执行完毕,就退出返回先结束的那个返回值

        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
}

getCompleted

这个是立刻获取协程异步执行的值

如果还没执行完毕就抛异常

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值