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

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:

主站蜘蛛池模板: 伊春市| 海兴县| 巴彦淖尔市| 淮滨县| 九龙城区| 丰顺县| 东港市| 乾安县| 盐亭县| 灵寿县| 绍兴县| 隆回县| 华池县| 达州市| 北海市| 泸水县| 龙胜| 武威市| 杨浦区| 黄大仙区| 深水埗区| 札达县| 吉安市| 万州区| 崇仁县| 隆林| 金寨县| 普安县| 岗巴县| 克东县| 布尔津县| 伊吾县| 井冈山市| 钦州市| 福清市| 平顺县| 泰安市| 健康| 黔西县| 寻甸| 寿光市|