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

相关推荐
V搜xhliang02464 分钟前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化
kaikaile199510 分钟前
风、浪、流环境模型的船舶三自由度(纵荡、横荡、艏摇)运动仿真MATLAB
开发语言·人工智能·matlab
fish_xk11 分钟前
map和set
java·开发语言
李崧正26 分钟前
Java技术分享:Lambda表达式与函数式编程
java·开发语言·python
老了,不知天命28 分钟前
鳶尾花項目JAVA
java·开发语言·机器学习
BIGmustang30 分钟前
python练手之用tkinter写一个计算器
开发语言·python
二哈赛车手35 分钟前
新人笔记---实现简易版的rag的bm25检索(利用ES),以及RAG上传时的ES与向量数据库双写
java·数据库·笔记·spring·elasticsearch·ai
winner888138 分钟前
从零吃透C++命名空间、std、#include、string、vector
java·开发语言·c++
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第26题:Java的抽象类和接口有哪些区别
java·开发语言·面试
bzmK1DTbd1 小时前
SOLID原则在Java中的实践:单一职责与开闭原则
java·开发语言·开闭原则