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

相关推荐
xiaoyan201535 分钟前
2026爆肝!Flutter3.41纯手撸微信聊天APP原生应用
android·flutter·dart
jinanwuhuaguo2 小时前
OpenClaw协议霸权——从 MCP 标准到意图封建化的政治经济学(第十八篇)
android·人工智能·kotlin·拓扑学·openclaw
撩得Android一次心动2 小时前
Android Room 数据库详解【源码篇】
android·数据库·android jetpack·room
TO_ZRG3 小时前
Android WorkManager 完全入门指南
android
a8a3023 小时前
Laravel 6.x新特性全解析
android
用户游民4 小时前
Android 腾讯X5WebView如何禁止系统自带剪切板和自定义剪切板视图
android·java
Lyyaoo.4 小时前
TreadLocal和TreadLocalMap
android·java·redis
CyL_Cly4 小时前
localsend安卓手机下载 支持win/mac/ubuntu
android·macos·智能手机
大尚来也4 小时前
防御现代Web威胁:使用PHP原生过滤器防止SQL注入与XSS的终极指南
android
idealzouhu4 小时前
【NDK开发】Android NDK 原生构建:ndk-build 与 CMake
android·ndk