理清子协程,父协程,协程效果域,协程生命周期,协程效果域的生命周期等的联系。
1、协程是在协程效果域内履行的轻量级并发单元。当协程的代码块履行完成时,它会挂起并返回到其父协程或顶层协程中。
2、父协程经过调用协程构建器(如 launch
、async
)来发动子协程。在发动子协程时,子协程会承继父协程的上下文(包括调度器、反常处理器等)。这意味着子协程会以与父协程相同的上下文履行。父协程能够经过 join()
办法等待子协程履行完成,以保证子协程的成果可用。
父协程能够经过撤销操作来撤销子协程。当父协程被撤销时,它会递归地撤销一切的子协程。子协程会接收到撤销事情,并根据撤销战略来决定怎么处理撤销。
父协程和子协程之间的联系能够协助管理协程的层次结构和生命周期。经过父协程发动和撤销子协程,能够有效地组织和控制协程的履行流程,完成更灵活和牢靠的协程编程。
fun main() {
runBlocking {
val parentJob = launch {
val childJob = launch {
printMsg("childJob start")
delay(500)
printMsg("childJob complete")
}
childJob.join()
printMsg("parentJob complete")
}
parentJob.join()
parentJob.cancel()
printMsg("parentJob cancel")
}
}
//日志
main @coroutine#3 childJob start
main @coroutine#3 childJob complete
main @coroutine#2 parentJob complete
main @coroutine#1 parentJob cancel
Process finished with exit code 0
fun main() {
runBlocking {
val parentJob = launch {
val childJob = launch {
printMsg("childJob start")
delay(500)
printMsg("childJob complete")
}
childJob.join()
printMsg("parentJob complete")
}
//parentJob.join() <----------改变在这里
parentJob.cancel()
printMsg("parentJob cancel")
}
}
//日志
main @coroutine#1 parentJob cancel
Process finished with exit code 0
3、协程效果域(CoroutineScope
)是用于协程的上下文环境,它供给了协程的发动和撤销操作的上下文。协程效果域界说了协程的生命周期,并决定了协程在何时发动、在何时撤销。
协程效果域是一个接口,界说了两个首要办法:
-
launch
:用于发动一个新的协程。launch
办法会创建一个新的协程,并将其添加到当前协程效果域中。发动的协程将承继父协程的上下文,并在协程效果域内履行。 -
cancel
:用于撤销协程效果域中的一切协程。cancel
办法会发送一个撤销事情到协程效果域中的一切协程,使它们退出履行。
协程效果域与协程之间的联系是协程在协程效果域内履行的。协程效果域为协程供给了上下文环境,使得协程能够访问到必要的上下文信息,例如调度器(Dispatcher
)和反常处理器(ExceptionHandler
)。经过在协程效果域中发动协程,能够保证协程的生命周期遭到协程效果域的管理,并且在协程效果域撤销时,一切协程都会被撤销。
fun main() = runBlocking {
coroutineScope {
launch {
delay(1000)
printMsg("Coroutine 1 completed")
}
launch(Job()) { <---------协程2不使用协程效果域的上下文,会脱离协程效果域的控制
delay(2000)
printMsg("Coroutine 2 completed")
}
}
printMsg("Coroutine scope completed")
}
//日志
main @coroutine#2 Coroutine 1 completed 1685615335423
main @coroutine#1 Coroutine scope completed 1685615335424 <-------协程1履行完,协程效果域就履行完
Process finished with exit code 0 <---------程序退出
4、假如使用 GlobalScope.launch
创建协程,则协程会成为大局协程,它的生命周期独立于程序的其他部分。当协程的代码履行结束后,大局协程不会主动退出,除非应用程序本身退出。因而,大局协程能够在整个应用程序的生命周期内持续履行,直到应用程序停止。
假如使用协程效果域(例如 runBlocking
、coroutineScope
等)创建协程,则协程的生命周期受协程效果域的约束。当协程的代码履行结束后,它会返回到效果域的父协程或尖端协程中,而不会主动退出。
5、当协程效果域内的一切协程履行完成后,协程效果域依然存在,但其间的协程会被标记为完成状况。这意味着协程效果域依然能够用于发动新的协程,但之前的协程不会再履行。
协程效果域的生命周期不仅仅依赖于其间的协程履行状况,还取决于其父协程或尖端协程的生命周期。假如协程效果域的父协程或尖端协程被撤销或完成,那么协程效果域也将被撤销。
fun main() = runBlocking {
coroutineScope {
launch {
delay(1000)
printMsg("Coroutine 1 completed")
}
launch {
delay(2000)
printMsg("Coroutine 2 completed")
}
}
printMsg("Coroutine scope completed")
}
//日志
main @coroutine#2 Coroutine 1 completed
main @coroutine#3 Coroutine 2 completed
main @coroutine#1 Coroutine scope completed
Process finished with exit code 0 <---------程序退出