初步使用kotlin协程的使用,协程相比线程,消耗更小
object CoroutineTest {
const val TAG = "CoroutineTest"
//runBlocking会阻塞主线程
fun testCoroutine() = runBlocking{
repeat(10)
{
Log.d(TAG, "Coroutine test $it thread id:${Thread.currentThread().id}")
// TimeUnit.SECONDS.sleep(1)
delay(1000)
}
}
//launch不会阻塞主线程
fun testLaunch() :Job {
return GlobalScope.launch {
testSuspend()
delay(5000)
Log.d(TAG, "launch end thread id:${Thread.currentThread().id}")
}
}
//suspend会将方法挂起,不会阻塞此方法后面的代码执行
suspend fun testSuspend() {
Log.d(TAG, "test suspend")
delay(1000)
}
fun testAsync() = GlobalScope.async {
testSuspend()
}
}
Kotlin学习体会-协程的使用
最新推荐文章于 2025-12-14 16:46:29 发布
本文介绍了如何在Kotlin中使用协程进行轻量级线程管理,通过`runBlocking`、`launch`和`suspend`函数展示了协程的优势,并以`testCoroutine`、`testLaunch`和`testSuspend`为例,详细讲解了不同方法的使用和效果。
432

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



