Android CoroutineScope Dispatchers.Main main thread delay, kotlin

Android CoroutineScope Dispatchers.Main main thread delay, kotlin

 

281a8cc76dea447f86b5e32a948edb4f.png

 

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    companion object {
        var TAG = "fly"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //点击按钮正常弹出Toast
        findViewById<Button>(R.id.button).setOnClickListener(object : OnClickListener {
            override fun onClick(v: View?) {
                Toast.makeText(
                    applicationContext,
                    TAG + " @${Thread.currentThread().id}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        })

        Log.d(TAG, "1 @${Thread.currentThread().id}")
        CoroutineScope(Dispatchers.Main).launch {
            delay(20_000)
            var id = Thread.currentThread().id
            Log.d(TAG, "launch @$id")
        }
        Log.d(TAG, "2 @${Thread.currentThread().id}")
    }
}

 

 

 

kotlin coroutineScope_zhangphil's blog-CSDN blog coroutineScope creates an independent coroutine scope, and does not end itself until all started coroutines are completed. runBlocking is very similar to coroutineScope, they both need to wait for all internal coroutines of the same scope to end before ending themselves. The main difference between the two is: runBlocking blocks the current thread, but coroutineScope will not, coroutineScope will suspend and release the underlying thread for other coroutines to use. kotlin coroutinecoroutineScope. https://blog.csdn.net/zhangphil/article/details/129265638

 

Guess you like

Origin blog.csdn.net/zhangphil/article/details/131295343