- 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:

- UI設計基礎培訓教程
- Expert C++
- Python應用輕松入門
- Unity Shader入門精要
- 深度學習:算法入門與Keras編程實踐
- Linux Device Drivers Development
- Bootstrap 4 Cookbook
- Learning PHP 7
- 深入理解C指針
- Visual C#(學習筆記)
- OpenStack Sahara Essentials
- Sony Vegas Pro 11 Beginner’s Guide
- Access 2013數(shù)據(jù)庫應用案例課堂
- iOS Application Development with OpenCV 3
- Android程序設計:第2版