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

相关推荐
HLC++20 小时前
Linux的进程间通信
android·linux·服务器
爱笑鱼1 天前
Binder(二):AIDL 生成的 Proxy、Stub 和 Parcel 到底在做什么?
android
爱笑鱼1 天前
Binder(一):一次方法调用,究竟怎样跨进程执行?
android
btown1 天前
Kotlin 版 MyBatis-Plus 查询优雅解决方案
kotlin
壮哥_icon1 天前
【Android 系统开发】使用 BAT 脚本高效自动化管理 /system/priv-app/ 系统应用(安装与卸载)
android·运维·自动化
用户69371750013841 天前
Claude Code终端日志Token占用实测:一个过滤器砍掉60%-90%
android·前端·后端
蝉蜕日记1 天前
AccumuPDF高级版 v2.57 | 视图文转换PDF,合并分割压缩
android·智能手机·pdf·生活·软件需求
吐了啊取名字太难1 天前
美颜系统AI修图本地跑并支持Mac、win、安卓、iOS不卡顿
android·人工智能·windows·数码相机·mac·ai编程
小二·1 天前
车载数字座舱实战:用魔珐星云打造下一代智能驾乘助手(附 Android/Kotlin 完整代码)
开发语言·kotlin
阿pin1 天前
Android随笔-Retrofit
android·retrofit