天天看點

kotlin 協程基礎

//1.開啟一個協程
private fun GlobalScopes() {
    GlobalScope.launch {//在背景啟動一個新協程
        delay(3000)//非阻塞延遲3秒
        println("你好!")
    }
    println("嗨,")
    Thread.sleep(3000)//主線程阻塞3秒
}
//2.主線程阻塞
private fun RunBlocking() {
    GlobalScope.launch {//在背景啟動一個新協程
        delay(3000)//非阻塞延遲3秒
        println("你好!")
    }
    println("嗨,")
    runBlocking {//阻塞主線程
        println("runBlocking.....")
        delay(1000)//非阻塞延遲3秒
        println("runBlocking...end")
    }
    println("運作結束")
}
//3.主線程阻塞 job.join
fun mainJoin()= runBlocking {
   var job=launch {
        delay(3000)
        println("nihao")
    }
    println("start")
    job.join()//等待協程先完成 再執行後面的
    println("end")
}
//4.coroutineScope
fun mainCoroutineScope()= runBlocking {
    launch {
        println("launch ...")
        delay(2000)
        println("launch ... end")
    }
    coroutineScope {//挂起函數 子協程結束後,才會結束自己
        launch {
            delay(500L)
            println("coroutineScope ...launch")
        }
        println("coroutineScope ...")
        delay(2000)
        println("coroutineScope ... end")
    }
}
//5.重構
fun mainSuspend()= runBlocking {
    launch {
        doThing()//提取函數重構
    }
    println("end")
}
suspend fun doThing() {//suspend修飾符
    delay(1000)
    println("doThing")
}
//6.守護線程
fun mainRepeat()= runBlocking {
    GlobalScope.launch {//全局協程類似于守護線程 當主線程消亡時,守護線程也将消亡
        repeat(10){
            i-> println("第$i")
            delay(1000)
            println("repeat....$i")
        }
    }
    delay(1300L)// just quit after delay
}