初步使用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学习体会-协程的使用
最新推荐文章于 2023-04-09 23:09:42 发布