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

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

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

相关推荐
studyForMokey4 小时前
【Android面试】Java专题 todo
android·java·面试
ZC跨境爬虫4 小时前
3D 地球卫星轨道可视化平台开发 Day6(SEC数据接口扩展实现)
前端·microsoft·3d·html·json·交互
一只大袋鼠4 小时前
MyBatis 特性(三):缓存、延迟加载、注解开发
java·数据库·笔记·sql·缓存·mybatis
qq_12084093714 小时前
Three.js 工程向:EffectComposer 后处理链路与色彩管理
开发语言·前端·javascript
|晴 天|4 小时前
评论系统与情感分析
前端·ai·typescript
老毛肚4 小时前
Redis高级
java·数据库·redis
沉默中爆发的IT男4 小时前
BGP基础配置实验总结
linux·服务器·前端
朝阳394 小时前
前端学习方法(含前端成神之路)
前端·学习方法
张元清5 小时前
head.tsx 就是一个 React 组件:用 loader 数据动态生成 SEO meta
前端·javascript·面试
lemon_yyds5 小时前
Element UI 实践踩坑- date-picker 组件 定制化type="daterange"
前端·css