阻塞与非阻塞
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.*
cla

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

被折叠的 条评论
为什么被折叠?



