协程

作者: 努力生活的西鱼 | 来源:发表于2024-01-01 18:20 被阅读0次
协程
- 协程: 是一种用于简化异步编程的技术,允许开发者以同步的方式编写非阻塞的代码,是一个新的线程框架。
1. GlobalScope.launch

GlobalScope.launch启动的协程,是和整个应用的生命周期挂扣的,即使Activity,Fragment被销毁,协程依然可能在运行。

// GlobalScope.launch启动一个顶层协程
GlobalScope.launch {
    // 协程的代码
    delay(5000) // 非阻塞的延迟5秒
    println("codes run in coroutine scope")
}

println("主线程继续执行")
2. runBlocking

runBlocking启动的协程会阻塞当前的线程,直到协程执行完毕。通常只应在测试环境下使用

// 阻塞主线程,等待协程执行完成
runBlocking {
    println("codes run in coroutine scope")
    delay(5000)
    println("codes run in coroutine scope finished")
}

println("主线程继续执行")

相关文章

网友评论

      本文标题:协程

      本文链接:https://www.haomeiwen.com/subject/ckiundtx.html