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

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:

主站蜘蛛池模板: 毕节市| 金川县| 阿拉善右旗| 个旧市| 蓝田县| 雅江县| 越西县| 建瓯市| 文安县| 枣庄市| 博客| 岐山县| 建德市| 玉屏| 公安县| 台北县| 井冈山市| 黄骅市| 兖州市| 河津市| 大英县| 巨鹿县| 惠东县| 马边| 东兴市| 澄城县| 奈曼旗| 普兰县| 垣曲县| 板桥市| 左贡县| 中卫市| 吉安县| 元谋县| 怀来县| 阳高县| 北安市| 盐山县| 温州市| 陇南市| 封丘县|