- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 240字
- 2021-08-05 10:46:44
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:

- 編程的修煉
- Practical UX Design
- 基于差分進(jìn)化的優(yōu)化方法及應(yīng)用
- 深入淺出DPDK
- C語言程序設(shè)計(jì)實(shí)踐教程
- Oracle BAM 11gR1 Handbook
- Visual FoxPro程序設(shè)計(jì)習(xí)題集及實(shí)驗(yàn)指導(dǎo)(第四版)
- Machine Learning in Java
- Visual Basic程序設(shè)計(jì)(第三版)
- 深入解析Java編譯器:源碼剖析與實(shí)例詳解
- LabVIEW數(shù)據(jù)采集
- 微信小程序開發(fā)邊做邊學(xué)(微課視頻版)
- H5匠人手冊(cè):霸屏H5實(shí)戰(zhàn)解密
- JavaScript語法簡(jiǎn)明手冊(cè)
- Java程序設(shè)計(jì)(項(xiàng)目教學(xué)版)