美文网首页
协程简单理解

协程简单理解

作者: yunhen | 来源:发表于2024-04-16 14:17 被阅读0次
    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}")
    
    }
    

    相关文章

      网友评论

          本文标题:协程简单理解

          本文链接:https://www.haomeiwen.com/subject/gxvjxjtx.html