Kotlin中协程的基本使用

本文介绍了Kotlin协程的四种创建方式:launch()、async()、withContext()和runBlocking(),详细解析了它们的使用场景和特点。此外,还探讨了Job和Deferred的概念,包括Job的状态管理和Deferred的返回值获取。

1.协程的创建方式

1.使用 launch()
  • 实例如下:
GlobalScope.launch {
        delay(3000)
    }
  • launch()函数的源代码如下:
public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

context :

接收一个可选的 CoroutineContext 参数,是一些元素的集合,主要包括 Job 和 CoroutineDispatcher 元素。可以代表一个协程的场景。默认值EmptyCoroutineContext,表示运行在父协程的上下文中。 其他值如下

  1. Dispatchers.Unconfined :协程调度器会在程序运行到第一个挂起点时,在调用者线程中启动。挂起后,它将在挂起函数执行的线程中恢复,恢复的线程完全取决于该挂

### 三级标题:Kotlin 协程的概念 Kotlin 协程是一种轻量级的并发编程模型,它允许以同步的方式编写异步代码。协程本质上是用户态的线程,可以在单个线程上高效地运行多个任务。它们通过挂起和恢复机制来实现非阻塞操作,从而避免了传统回调地狱的问题[^2]。 ### 三级标题:Kotlin 协程基本使用方法 #### 启动协程Kotlin 中,可以使用 `launch` 和 `async` 来启动协程。`launch` 通常用于启动一个不需要返回结果的协程,而 `async` 则用于需要返回结果的情况。两者都可以在特定的作用域内启动协程,例如 `GlobalScope` 或者 `coroutineScope`。 ```kotlin import kotlinx.coroutines.* fun main() = runBlocking { // this: CoroutineScope launch { // 在 GlobalScope 中启动一个新的协程 delay(1000L) println("World!") } println("Hello,") delay(2000L) // 等待直到子协程完成 } ``` #### 挂起函数 挂起函数只能在协程内部调用,或者由其他挂起函数调用。最常用的挂起函数之一是 `delay`,它可以暂停当前协程一段时间而不阻塞线程[^5]。 ```kotlin suspend fun doSomething() { delay(1000) println("Done something") } ``` #### 结构化并发 `coroutineScope` 是 Kotlin 协程中实现结构化并发的核心 API。所有在 `coroutineScope` 内启动的子协程都会与该作用域绑定,并且 `coroutineScope` 会等待所有子协程完成后才返回。此外,任一子协程抛出异常会导致整个作用域取消[^4]。 ```kotlin fun main() = runBlocking { coroutineScope { launch { println("Child coroutine 1 started") delay(500) println("Child coroutine 1 finished") } launch { println("Child coroutine 2 started") delay(300) println("Child coroutine 2 finished") } } println("All child coroutines have completed.") } ``` #### 上下文切换 使用 `withContext` 可以切换协程的执行上下文,比如在 IO 线程中进行一些阻塞性操作[^3]。 ```kotlin fun main() = runBlocking { val result = withContext(Dispatchers.IO) { // 执行耗时操作 "Result from IO" } println(result) } ``` ### 三级标题:简单的协程示例 下面是一个结合了上述概念的简单示例: ```kotlin import kotlinx.coroutines.* fun main() = runBlocking { println("Start of main") // 使用 launch 启动一个协程 val job = launch { println("Start of launched coroutine") delay(1000) println("End of launched coroutine") } // 使用 async 获取结果 val deferred = async { println("Start of async coroutine") delay(500) "Result from async" } // 等待 async 完成并打印结果 println(deferred.await()) // 等待 launch 完成 job.join() println("End of main") } ``` 在这个例子中,我们展示了如何使用 `launch` 和 `async` 来启动协程,并演示了如何使用 `await` 来获取 `async` 的结果以及如何使用 `join` 来等待 `launch` 的完成。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值