//1.按顺序执行
fun main1() = runBlocking<Unit> {
val time = measureTimeMillis { //计算时间
var one = doOne()
var two = doTwo()
println("onetwo Time is ${one+two}")//相加
}
println("Time is ${time}")
}
suspend fun doOne(): Int {
delay(1000)//延迟1秒
return 1
}
suspend fun doTwo(): Int {
delay(2000)//延迟2秒
return 2
}
//2.并发执行 async
fun mainAsync() = runBlocking<Unit> {
val time = measureTimeMillis { //计算时间
var one = async { doOne()}// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象
var two = async { doTwo()}//
println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值
}
println("Time is ${time}")
}
//3.惰性启动
fun mainLazy() = runBlocking<Unit> {
val time = measureTimeMillis { //计算时间
var one = async(start = CoroutineStart.LAZY) { doOne()}// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象
var two = async (start = CoroutineStart.LAZY){ doTwo()}
one.start()//开始执行协程 ,注意如果 先调用await() 会启动协程并等待其完成
two.start()
println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值
}
println("Time is ${time}")
}
//4.并发结构
fun main_async1() = runBlocking<Unit> {
val time = measureTimeMillis { //计算时间
doThings()
}
println("Time is ${time}")
}
suspend fun doThings():Int=coroutineScope {
var one = async() { doOnes() }// async 启动一个单独的协程 返回一个轻量级非阻塞的 Deferred 对象
var two = async() { doTwos() }
println("onetwo Time is ${one.await()+two.await()}")//one.await()获取返回的值
one.await() + two.await()//one.await()获取返回的值
}
suspend fun doOnes(): Int {
delay(1000) // pretend we are doing something useful here
return 1
}
suspend fun doTwos(): Int {
delay(2000) // pretend we are doing something useful here
return 2
}
fun main_async2() = runBlocking<Unit> {
try {
currentSum()
}catch (e:Exception){
println("main_async2 Exception..")
}
}
suspend fun currentSum():Int= coroutineScope {
val one=async<Int> {
try {
delay(1000)
}finally {
println("one finally")
}
1
}
val two=async<Int> {
delay(2000)
println("two exception..")
throw ArithmeticException()//先子类协程抛异常 然后父类协程再抛异常
}
one.await()+two.await()
}
kotlin 组合挂起函数
最新推荐文章于 2025-06-18 21:30:00 发布
本文介绍了Kotlin中使用协程实现的四种并发执行方式:顺序执行、并发执行(async)、惰性启动(lazy)以及并发结构(coroutineScope)。通过示例代码展示了如何测量执行时间和控制协程执行流程,强调了提高程序效率和资源利用率的重要性。
920

被折叠的 条评论
为什么被折叠?



