协程简单理解

2024-04-16  本文已影响0人  yunhen
suspend fun sf1(){
    Log.e(MainActivity.TAG,"testSuspendFun1_sf1_04,当前线程:${Thread.currentThread().name}")
//    delay(3000)
    var x = 0;
    for(i in 1..1000000000){
        x += i
    }
    Log.e(MainActivity.TAG,"testSuspendFun1_sf1_05,当前线程:${Thread.currentThread().name}")
}

launch

fun testSuspendFun1(){
    val mScope = MainScope()

    //执行顺序 1
    Log.e(MainActivity.TAG,"testSuspendFun1_01,当前线程:${Thread.currentThread().name}")
    mScope.launch {
        //创建并运行一个异步 ,但不是切换线程
        //执行顺序 3
        Log.e(MainActivity.TAG,"testSuspendFun1_03,当前线程:${Thread.currentThread().name}")
        //执行顺序 4
        sf1()

        //执行顺序 5
        Log.e(MainActivity.TAG,"testSuspendFun1_06,当前线程:${Thread.currentThread().name}")
    }
    //执行顺序 2
    Log.e(MainActivity.TAG,"testSuspendFun1_02,当前线程:${Thread.currentThread().name}")


}


async

fun testSuspendFun2(){
    val mScope = MainScope()
    //执行顺序 1
    Log.e(MainActivity.TAG,"testSuspendFun2,01,当前线程:${Thread.currentThread().name}")
    val job = mScope.launch {
        //创建并运行一个异步 ,但不是切换线程
        //执行顺序 3
        Log.e(MainActivity.TAG,"testSuspendFun2,03,当前线程:${Thread.currentThread().name}")


        val deferred = this.async {
            //创建一个异步,暂时不运行
            //执行顺序 6
            Log.e(MainActivity.TAG,"testSuspendFun2,06,当前线程:${Thread.currentThread().name}")
            sf1()
            1
        }
        //执行顺序 4
        Log.e(MainActivity.TAG,"testSuspendFun2,04,当前线程:${Thread.currentThread().name}")
        sf1()
        //执行顺序 5
        Log.e(MainActivity.TAG,"testSuspendFun2,05,当前线程:${Thread.currentThread().name}")
        val result = deferred.await()

        //执行顺序 7
        Log.e(MainActivity.TAG,"testSuspendFun2,07,当前线程:${Thread.currentThread().name}")
    }


    //执行顺序 2
    Log.e(MainActivity.TAG,"testSuspendFun2,02,当前线程:${Thread.currentThread().name}")

}
上一篇 下一篇

猜你喜欢

热点阅读