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

相关推荐
皮皮林5514 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河4 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程7 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅9 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者10 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺10 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart11 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP12 小时前
MyBatis-mybatis入门与增删改查
java
孟陬15 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端