withContext

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

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

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

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: