- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 206字
- 2021-08-05 10:46:52
Active
A job in the state new can be started in many ways, but commonly it will be done by calling start() or join(), the difference being that the former will start the job without waiting for it to complete, whereas the latter will suspend execution until the job completes. Take this example into consideration:
fun main(args: Array<String>) {
val job = launch(start = CoroutineStart.LAZY) {
delay(3000)
}
job.start()
}
The mentioned code will not suspend execution when job.start() is invoked, so the application will complete its execution without waiting for job to complete.
Since start() doesn't suspend execution, it doesn't need to be called from a suspending function or coroutine. It can be called from any part of our application.
If we use join(),we will force the application to wait for job to complete, as demonstrated:
fun main(args: Array<String>) = runBlocking {
val job = launch(start = CoroutineStart.LAZY) {
delay(3000)
}
job.join()
}
As join() can suspend execution, it needs to be called from a coroutine or a suspending function. Note that runBlocking() is being used for that.
Any job that has been started is therefore active, and it will be active until it completes execution or until cancellation is requested.
推薦閱讀
- Deploying Node.js
- PostgreSQL Cookbook
- 深入理解Django:框架內(nèi)幕與實現(xiàn)原理
- MariaDB High Performance
- Symfony2 Essentials
- Cocos2d-x學(xué)習(xí)筆記:完全掌握Lua API與游戲項目開發(fā) (未來書庫)
- 深入RabbitMQ
- Jupyter數(shù)據(jù)科學(xué)實戰(zhàn)
- .NET 3.5編程
- MySQL入門很輕松(微課超值版)
- R用戶Python學(xué)習(xí)指南:數(shù)據(jù)科學(xué)方法
- C++程序設(shè)計
- 零基礎(chǔ)學(xué)C++(升級版)
- 青少年學(xué)Python(第2冊)
- 高效使用Greenplum:入門、進(jìn)階與數(shù)據(jù)中臺