協(xié)程的定義
協(xié)程可以理解為一種輕量級的線程。
協(xié)程和線程的區(qū)別是線程是依靠操作系統(tǒng)的調(diào)度才能實(shí)現(xiàn)不同線程之間的切換的,而協(xié)程可以在編程語言層面就能實(shí)現(xiàn)不同協(xié)程之間的切換,大大提升了并發(fā)編程的效率。
1.GlobalScope.launch創(chuàng)建的是頂層協(xié)程,當(dāng)應(yīng)用程序結(jié)束運(yùn)行時,也會一起結(jié)束,所以下面的代碼如果不寫Thread.sleep那么協(xié)程里面的代碼就不會打印。delay()函數(shù)可以掛起協(xié)程。
GlobalScope.launch {
println("codes run in coroutine scope")
delay(1500)
println("codes run in coroutine scope finished")
}
Thread.sleep(1000)
2.runBlocking所創(chuàng)建的協(xié)程,會阻塞當(dāng)前線程,指導(dǎo)作用域內(nèi)的所有代碼和子協(xié)程都執(zhí)行完畢。不過這個方法很影響性能,一般只在測試代碼中使用
runBlocking {
println("codes run in coroutine scope")
delay(1500)
println("codes run in coroutine scope finished")
launch {
println("launch1")
delay(1000)
println("launch1 finished")
}
launch {
println("launch2")
delay(1000)
println("launch2 finished")
}
}
使用了suspend聲明的方法才可以協(xié)程當(dāng)中調(diào)用,但是不提供協(xié)程的作用域。
suspend fun printDot(){
println(".")
delay(1000)
}
3.coroutineScope函數(shù)也是一個掛起函數(shù),并且可以繼承外部的作用域同時創(chuàng)建一個子協(xié)程。也會掛起外部協(xié)程。
suspend fun printDot2()= coroutineScope {
launch {
println(".")
delay(1000)
}
}
Global.launch、runBlocking、launch、coroutineScope都可以創(chuàng)建一個新的協(xié)程,但是Global.launch、runBlocking是可以在任意地方調(diào)用的,coroutineScope可以在協(xié)程和掛起函數(shù)中調(diào)用,launch只能在協(xié)程作用域中調(diào)用
實(shí)際開發(fā)中基本上使用CoroutineScope來創(chuàng)建協(xié)程,因?yàn)榉奖憧刂?/p>
val job= Job()
val scope= CoroutineScope(job)
scope.launch {
}
scope.cancel()
4.async函數(shù)用來創(chuàng)建一個協(xié)程并且獲得一個Deferred對象,然后調(diào)用await方法來獲取執(zhí)行結(jié)果。當(dāng)調(diào)用await方法是會阻塞協(xié)程,直到async拿到了
fun main(){
runBlocking {
val result=async {
5+5
}.await()
println(result)
}
}