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

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

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

相关推荐
小着1 小时前
vue项目页面最底部出现乱码
前端·javascript·vue.js·前端框架
JH30731 小时前
Java Stream API 在企业开发中的实战心得:高效、优雅的数据处理
java·开发语言·oracle
九月十九4 小时前
java使用aspose读取word里的图片
java·word
lichenyang4534 小时前
React ajax中的跨域以及代理服务器
前端·react.js·ajax
呆呆的小草4 小时前
Cesium距离测量、角度测量、面积测量
开发语言·前端·javascript
一 乐5 小时前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
爱记录的小磊5 小时前
java-selenium自动化快速入门
java·selenium·自动化
鹏码纵横5 小时前
已解决:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 异常的正确解决方法,亲测有效!!!
java·python·mysql
weixin_985432115 小时前
Spring Boot 中的 @ConditionalOnBean 注解详解
java·spring boot·后端