kotlin runBlocking函数

测试下runBlocking函数执行流程。

Kotlin 复制代码
private fun testRunBlocking() {
    Log.d("zxzx", "testRunBlocking start, currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    fun runBlockingFunction() = runBlocking {
        Log.d("zxzx", "testRunBlocking runBlocking start, currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
        delay(2000L)
        Log.d("zxzx", "testRunBlocking runBlocking end , currThread:${Thread.currentThread().name} , currTime:" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    }

    Log.d("zxzx", "testRunBlocking start 1,  currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    runBlockingFunction()
    Log.d("zxzx", "testRunBlocking end 1,  currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
}

在主线程调用testRunBlocking函数。 打印:

ok. 这里调用RunBlocking函数没有指定上下文, 还是在原来的main函数执行runBlocking的代码块。该代码块后面的代码流程会被阻塞。等runBlocking块执行完之后再执行下面的代码。

再测试下,runBlocking函数传Dispatchers.IO参数,其他都不变。

Kotlin 复制代码
private fun testRunBlocking2() {
    Log.d("zxzx", "testRunBlocking start, currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    fun runBlockingFunction() = runBlocking(Dispatchers.IO) {
        Log.d("zxzx", "testRunBlocking runBlocking start, currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
        delay(2000L)
        Log.d("zxzx", "testRunBlocking runBlocking end , currThread:${Thread.currentThread().name} , currTime:" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    }

    Log.d("zxzx", "testRunBlocking start 1,  currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
    runBlockingFunction()
    Log.d("zxzx", "testRunBlocking end 1,  currThread:${Thread.currentThread().name} ,currTime: " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
}

还是主线程调用, 日志打印:

ok. 区别是runBlocking代码块被切换到一个IO线程执行了,执行这个代码块会阻塞主线程,等这个代码块执行完之后再执行下面的代码。

相关推荐
三少爷的鞋2 小时前
别再 launch(IO) 了:协程线程切换的 3隐藏反模式
android
贤泽4 小时前
Android 15 Lock Task 模式深度分析(第二部分)
android
huohuopro4 小时前
Vue3 Webview 转 Android 虚拟导航栏遮挡问题记录
android·vue
zh_xuan4 小时前
kotlin 挂起函数
android·开发语言·kotlin
贤泽5 小时前
Android 15 Lock Task 模式深度分析(第一部分)
android
zh_xuan5 小时前
kotlin launch函数
android·kotlin·协程·launch
贤泽6 小时前
android 15 AOSP Broadcast 广播机制源码分析
android·aosp
啥都想学点6 小时前
第1天:搭建 flutter 和 Android 环境
android·flutter
huohuopro6 小时前
Android WebView 输入法同步问题解决方案
android