Kotlin 协程基础 | Kotlin 入门教程指南

本文介绍了Kotlin协程的基础,包括非阻塞特性和结构化并发。通过runBlocking、coroutineScope和GlobalScope演示了协程的使用,强调了在协程中避免阻塞主线程的重要性。此外,还讨论了协程的轻量级特性,以及如何通过提取函数进行代码重构。文章最后提到了Kotlin入门教程,覆盖了从基础到协程的多个主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

阻塞与非阻塞

runBlocking

delay是非阻塞的,Thread.sleep是阻塞的。显式使用 runBlocking 协程构建器来阻塞。

import kotlinx.coroutines.*

fun main() {
   
    GlobalScope.launch {
    // 在后台启动一个新的协程并继续
        delay(200)
        "rustfisher.com".forEach {
   
            print(it)
            delay(280)
        }
    }
    println("主线程中的代码会立即执行")
    runBlocking {
        // 这个表达式阻塞了主线程
        delay(3000L)  //阻塞主线程防止过快退出
    }
    println("\n示例结束")
}

可以看到,runBlocking里使用了delay来延迟。用了runBlocking的主线程会一直阻塞直到runBlocking内部的协程执行完毕。 也就是runBlocking{ delay }实现了阻塞的效果。

我们也可以用runBlocking来包装主函数。

import kotlinx.coroutines.*

fun main() = runBlocking {
   
    delay(100) // 在这里可以用delay了

    GlobalScope.launch {
   
        delay(100)
        println("Fisher")
    }
    print("Rust ")
    delay(3000)
}

runBlocking<Unit>中的<Unit>目前可以省略。
runBlocking也可用在测试中

// 引入junit
dependencies {
   
    implementation("junit:junit:4.13.1")
}

测试

使用@Test设置测试

import org.junit.Test
import kotlinx.coroutines.*

class 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值