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

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:

主站蜘蛛池模板: 五大连池市| 新乡市| 浦县| 汉川市| 昌吉市| 颍上县| 赤壁市| 昭平县| 遵义市| 楚雄市| 和硕县| 阿克陶县| 区。| 金华市| 紫云| 蒲江县| 桐柏县| 建始县| 清苑县| 青阳县| 霸州市| 大方县| 池州市| 岐山县| 无为县| 成都市| 彩票| 台山市| 肇州县| 色达县| 乐清市| 广汉市| 金沙县| 兴海县| 赤水市| 贺兰县| 绥德县| 喀喇沁旗| 宁乡县| 新兴县| 万盛区|