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线程执行了,执行这个代码块会阻塞主线程,等这个代码块执行完之后再执行下面的代码。

相关推荐
天***88528 小时前
安卓KMPlayer安卓版播放器,支持AC-3、WMA、MP3、AAC
android·aac
jinanwuhuaguo9 小时前
OpenClaw 2026.4.5 深度解读
android·开发语言·人工智能·kotlin·openclaw
用户69371750013849 小时前
实测!Gemma 4 成功跑在安卓手机上:离线 AI 助手终于来了
android·前端·人工智能
海兰9 小时前
使用 Elastic Workflows 监控 Kibana 仪表板访问数据
android·人工智能·elasticsearch·rxjava
用户483916550839 小时前
AI代码分析 - LocklessQueue
android
峥嵘life10 小时前
Android 无线投屏相关知识介绍
android·学习
常利兵10 小时前
安卓开发避坑指南:全局异常捕获与优雅处理实战
android·服务器·php
studyForMokey10 小时前
【Android面试】OkHttp & Retrofit 专题
android·okhttp·面试
恋猫de小郭10 小时前
抖音“极客”适配 Android 5 ~ 9 等老机型技术解读,都是骚操作
android·前端·flutter
黄林晴10 小时前
Android Studio Panda 4 来了!AGP 9.2 升级,同步稳定性大幅修复
android·android studio