kotlin 挂起函数

测试下挂起函数:

Kotlin 复制代码
// 1. 定义挂起函数(用suspend关键字修饰)
suspend fun suspendFunction(name: String, delayTime: Long) {
    Log.d("zxzx", "[$name] 挂起函数开始执行,当前线程:${Thread.currentThread().name}")

    // delay是Kotlin内置的挂起函数(核心:释放线程,不阻塞)
    delay(delayTime)

    Log.d("zxzx", "[$name] 挂起函数执行完毕,当前线程:${Thread.currentThread().name}")
}

// 2. 测试函数(Android环境可放在Activity/Fragment中,普通测试用main函数)
fun testSuspend() {
    Log.d("zxzx", "主线程开始,当前线程:${Thread.currentThread().name}")

    // 错误示例:普通函数中直接调用挂起函数 → 编译报错!
    // suspendFunction("错误测试", 1000L) // 编译提示:Suspend function 'suspendFunction' should be called only from a coroutine or another suspend function

    // 正确方式1:在runBlocking(协程作用域)中调用
    runBlocking {
        // 启动子协程调用挂起函数
        launch(Dispatchers.IO) {
            suspendFunction("测试1", 2000L)
        }
        launch(Dispatchers.Default) {
            suspendFunction("测试2", 1000L)
        }
    }

    // 正确方式2:Android中用lifecycleScope(推荐)
    // lifecycleScope.launch {
    //     suspendFunction("Android测试", 1500L)
    // }

    Log.d("zxzx", "主线程继续执行,当前线程:${Thread.currentThread().name}")
    Log.d("zxzx", "力拔山兮气盖世,\n时不利兮骓不逝。\n骓不逝兮可奈何,\n虞兮虞兮奈若何!")
}

在onCreate函数中调用testSuspend函数,打印:

ok. 这里好像没看出挂起有什么用。后面再继续研究。

相关推荐
白杨尚青27 分钟前
C++进阶篇(五):红黑树——四条规则、三种插入情况与旋转变色
开发语言·数据结构·c++·stl·红黑树·平衡二叉树
.道阻且长.34 分钟前
Linux基本开发工具:gdb和cgdb的使用
linux·运维·服务器·开发语言
恋猫de小郭1 小时前
Flutter 下 AOT 一个你怎么都想不出来的 Bug ,JIT 正常的计算,在 AOT 居然算错了
android·前端·flutter
starzy19901 小时前
深入理解Scala匿名函数:函数式编程基石
开发语言·scala
apcipot_rain2 小时前
C++转Java日记(05)
java·开发语言·c++
apcipot_rain11 小时前
C++转Java日记(04)
java·开发语言·c++
云和数据.ChenGuang12 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
金銀銅鐵13 小时前
同一个 Hello World,Kotlin 和 Java 在字节码层面差在哪
jvm·后端·kotlin
蜗牛一步步往上爬15 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
好的佩奇17 小时前
Dart 之扩展方法
android·flutter·dart