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 关键字通常用于当函数作为参数传递时,以避免函数调用带来的性能损失。

相关推荐
静心观复1 天前
drawio画java的uml的类图时,class和interface的区别是什么
java·uml·draw.io
moringlightyn1 天前
c++11可变模版参数 emplace接口 新的类功能 lambda 包装器
开发语言·c++·笔记·其他·c++11·lambda·包装器
Laplaces Demon1 天前
Spring 源码学习(十四)—— HandlerMethodArgumentResolver
java·开发语言·学习
郝学胜-神的一滴1 天前
使用Linux系统函数递归遍历指定目录
linux·运维·服务器·开发语言·c++·软件工程
guygg881 天前
Java 无锁方式实现高性能线程
java·开发语言
ss2731 天前
手写Spring第7弹:Spring IoC容器深度解析:XML配置的完整指南
java·前端·数据库
青衫码上行1 天前
【从0开始学习Java | 第22篇】反射
java·开发语言·学习
superlls1 天前
(Spring)Spring Boot 中 @Valid 与全局异常处理器的联系详解
java·spring boot·后端
一念&1 天前
每日一个C语言知识:C 字符串
c语言·开发语言
0110_10241 天前
tauri + rust的环境搭建---初始化以及构建
开发语言·后端·rust