Kotlin Async

Kotlin 复制代码
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
}
Kotlin 复制代码
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<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
}
Kotlin 复制代码
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<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

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

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

相关推荐
大怪v2 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习2 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
皮皮林5512 小时前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
小兵张健2 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒5 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat5 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
代码老中医5 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
不会敲代码15 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫5 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川5 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能