使用await时异步阻塞吗 [英] Does async block when using await

查看:793
本文介绍了使用await时异步阻塞吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,运行两个异步:

In the following code two asyncs are run:

import kotlinx.coroutines.*
import kotlin.system.*

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async { doSomethingUsefulOne() }
        val two = async { doSomethingUsefulTwo() }
        two.await()
        one.await()
        println("Finished")
    }   
}

suspend fun doSomethingUsefulOne(): Int {
    delay(3000L)
    println("first")
    return 13
}

suspend fun doSomethingUsefulTwo(): Int {
    delay(1000L)
    println("second")
    return 29
}

为什么不首先打印完成"?文档说了关于await:

Why is "Finished" not printed first? The docs says this about await:

等待该值完成而不会阻塞线程

Awaits for completion of this value without blocking a thread

推荐答案

通过稍微修改代码,人们将获得一些见解.让我们将经过的时间和当前线程添加到打印语句中,以查看发生了什么:

By slightly modifying the code, one will gain some insights. Let's add the elapsed time and the current thread to the print statements to see, what's going on:

在科特林游乐场执行

import kotlinx.coroutines.*
import kotlin.system.*

private val started = System.currentTimeMillis()

private fun debug(s: String) {
    val elapsed = System.currentTimeMillis() - started
    println("[$elapsed] $s  --  ${Thread.currentThread()}")
}

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async { doSomethingUsefulOne() }
        val two = async { doSomethingUsefulTwo() }
        debug("awaiting")
        two.await()
        one.await()
        debug("Finished")
    }
    debug("time = $time")
}

suspend fun doSomethingUsefulOne(): Int {
    delay(3000L)
    debug("first")
    return 13
}

suspend fun doSomethingUsefulTwo(): Int {
    delay(1000L)
    debug("second")
    return 29
}

-Dkotlinx.coroutines.debug一起运行时,应该会看到类似于

When run with -Dkotlinx.coroutines.debug one should see something similar to

[46] awaiting  --  Thread[main @coroutine#1,5,main]
[1056] second  --  Thread[main @coroutine#3,5,main]
[3054] first  --  Thread[main @coroutine#2,5,main]
[3054] Finished  --  Thread[main @coroutine#1,5,main]
[3054] time = 3013  --  Thread[main @coroutine#1,5,main]

只有一个线程.

如果await阻止了线程,则程序可能不会终止.

If await had blocked the thread, the program could not have terminated.

这篇关于使用await时异步阻塞吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆