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

相关推荐
Kapaseker17 小时前
Kotlin 解构新语法完全解析:从"看位置"到"看名字"
android·kotlin
阿正的梦工坊17 小时前
Kotlin 中的 ?. 和 . 语法详解
开发语言·python·kotlin
禁默17 小时前
解密 LangChain:LLM 应用开发的核心框架与“超级武器”
android·adb·langchain·vibe coding
小肝一下17 小时前
5. 基础IO
android·linux·shell·基础io·操作系统底层·伊涅夫·伊雷娜
Fate_I_C18 小时前
View Binding与Data Binding 核心区别及实战指南
android·kotlin·viewbinding·databinding
阿正的梦工坊18 小时前
Kotlin:现代编程语言的优雅之选
android·开发语言·kotlin
敲代码的鱼哇18 小时前
NFC读卡能力 支持安卓/iOS/鸿蒙 UTS插件
android·ios·harmonyos
new_bie_B1 天前
Android16 Input 事件分发链路
android
TDengine (老段)1 天前
TDengine RAFT共识协议 — 选举、日志复制、快照与仲裁
android·大数据·数据库·物联网·架构·时序数据库·tdengine
YF02111 天前
深入剖析 Kotlin 的高效之道与核心实战
android·kotlin·app