官术网_书友最值得收藏!

Being explicit

Concurrency needs to be thought about and designed for, and because of that, it's important to make it explicit in terms of when a computation should run concurrently. Suspendable computations will run sequentially by default. Since they don't block the thread when suspended, there's no direct drawback:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val name = getName()
val lastName = getLastName()
println("Hello, $name $lastName")
}
println("Execution took $time ms")
}

suspend fun getName(): String {
delay(1000)
return "Susan"
}

suspend fun getLastName(): String {
delay(1000)
return "Calvin"
}

In this code, main() executes the suspendable computations getName() and getLastName() in the current thread, sequentially.

Executing main() will print the following:

This is convenient because it's possible to write non-concurrent code that doesn't block the thread of execution. But after some time and analysis, it becomes clear that it doesn't make sense to have getLastName() wait until after getName() has been executed since the computation of the latter has no dependency on the former. It's better to make it concurrent:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val name = async { getName() }
val lastName = async { getLastName() }

println("Hello, ${name.await()} ${lastName.await()}")
}
println("Execution took $time ms")
}

Now, by calling async {...} it's clear that both of them should run concurrently, and by calling await() it's requested that main() is suspended until both computations have a result:

主站蜘蛛池模板: 马公市| 西安市| 荥经县| 柘城县| 东城区| 化隆| 鄱阳县| 任丘市| 台南县| 聂荣县| 诸城市| 菏泽市| 会同县| 福贡县| 盐城市| 张北县| 大冶市| 高邑县| 微山县| 根河市| 海丰县| 育儿| 炉霍县| 周至县| 南木林县| 凤冈县| 龙南县| 禹州市| 阳原县| 合作市| 卓尼县| 理塘县| 伊川县| 团风县| 高青县| 阿拉善左旗| 恩施市| 资阳市| 万荣县| 当涂县| 运城市|