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

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

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

相关推荐
龙在天2 分钟前
ts中的函数重载
前端
卓伊凡18 分钟前
非常经典的Android开发问题-mipmap图标目录和drawable图标目录的区别和适用场景实战举例-优雅草卓伊凡
前端
前端Hardy18 分钟前
HTML&CSS: 谁懂啊!用代码 “擦去”图片雾气
前端·javascript·css
前端Hardy20 分钟前
HTML&CSS:好精致的导航栏
前端·javascript·css
Java中文社群24 分钟前
重要:Java25正式发布(长期支持版)!
java·后端·面试
天下无贼32 分钟前
【手写组件】 Vue3 + Uniapp 手写一个高颜值日历组件(含跨月补全+今日高亮+选中状态)
前端·vue.js
我是天龙_绍33 分钟前
🔹🔹🔹 vue 通信方式 eventBus
前端
一个不爱写代码的瘦子1 小时前
迭代器和生成器
前端·javascript
拳打南山敬老院1 小时前
漫谈 MCP 构建之概念篇
前端·后端·aigc
前端老鹰1 小时前
HTML <output> 标签:原生表单结果展示容器,自动关联输入值
前端·html