Kotlin withContext详解与suspend和inline

withContext

Kotlin 复制代码
package com.tiger.mykotlinapp.scope

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

@OptIn(ExperimentalStdlibApi::class)
fun main() {
    runBlocking(Dispatchers.IO) {

        println(coroutineContext.get(CoroutineDispatcher).toString())
        launch {

            //挂起操作,阻塞当前协程
            val res = withContext(Dispatchers.Default) {
                delay(2000)
                println(coroutineContext.get(CoroutineDispatcher).toString())
                1
            }

        }

      
        println(coroutineContext.get(CoroutineDispatcher).toString())


    }


}

suspend

Kotlin 复制代码
package com.tiger.mykotlinapp.scope

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

@OptIn(ExperimentalStdlibApi::class)
fun main() {

    // 协程就是代码块,由一个线程去调度任务去分别执行协程。
    runBlocking {
        launch {
            val test4 = test4()
            println(test4)
        }

        println("aaa")

    }

    println("hello")
}
//suspend就是一个标识符,用于协程代码块
suspend fun test4():Int{
    delay(10000)
    return 1
}

inline

Kotlin 复制代码
package com.tiger.mykotlinapp.scope

fun main() {
    val test = test10(3){
        println(it)
    }
}
//inline使用场景是以函数作为参数来使用的时候 做的一个修饰符  就是可以把方法体的内容直接复制到调用方法里,不用堆栈,减少时间,以空间换时间
inline fun test10(i: Int, finish: (Int) -> Unit) {
    println("之前的内容 $i")
    finish(i.inc())
}

在这段代码中,inline 关键字用于修饰 test10 函数,这意味着编译器会将函数体内的代码直接复制到调用 test10 函数的地方,而不会创建一个函数调用的堆栈。这样的优化可以减少函数调用的时间开销,以提高程序的性能。inline 关键字通常用于当函数作为参数传递时,以避免函数调用带来的性能损失。

相关推荐
南棱笑笑生3 小时前
20260904实测给飞凌OK3576-C开发板刷入Rockchip原厂的IMG固件【使用飞凌的DTS】切换串口波特率为1.5Mbps
c语言·开发语言·rockchip
zhanghe6873 小时前
es的密码带有特殊字符,导出
java
平头哥技术团队4 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
pnoker4 小时前
IoT DC3 概念解读:把设备抽象成一套语义模板——位号、指令、事件与面向智能体的设备建模
java·人工智能·物联网·iot·dc3
乌萨奇也要立志学C++4 小时前
【洛谷】kmp算法
开发语言·算法
my_realmy4 小时前
Java SE 基础学习笔记(一):面向对象、继承多态、抽象接口与异常(JDK 8)
java·多线程·并发··生产者消费者模式
传奇开心果编程4 小时前
【Rust入门知识点学与练】第4课:条件判断 if / else
开发语言·学习·rust
m0_380743874 小时前
给 Claude API 调用补上超时重试和错误分类
开发语言·人工智能·php
天远数科4 小时前
风险治理实战:基于天远车信盟出险构建自动化理赔核保流水线
java·网络·人工智能·自动化
Draw Stars4 小时前
Git BASH安装教程
开发语言·git·bash