知乎专栏 |
GlobalScope.launch { while (true) { delay(1000) println("每秒执行一次") } }
GlobalScope.launch { //GlobalScope开启协程:DefaultDispatcher-worker-1 Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name) //子线程中此处不可以做UI操作 withContext(Dispatchers.Main){ Toast.makeText(this@MainActivity, "协程中切换线程", Toast.LENGTH_SHORT).show() } }
GlobalScope.launch(Dispatchers.Main) { //GlobalScope开启协程:main Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name) //可以做UI操作 Toast.makeText(this@MainActivity, "GlobalScope开启协程", Toast.LENGTH_SHORT).show() }
lifecycleScope默认主线程,可以通过withContext来指定线程
lifecycleScope.launch { // do withContext(Dispatchers.IO) { // do } } // or lifecycleScope.launch(Dispatchers.IO){ // do } // or lifecycleScope.launch { whenResumed { // do } } // or lifecycleScope.launchWhenResumed { // do }
private fun serialExecution() { lifecycleScope.launch { val startTime = System.currentTimeMillis() val a = getDataA() val b = getDataB() val sum = a + b //D/MainActivity: serialExecution: sum = 3,耗时:3008 Log.d(TAG, "serialExecution: sum = $sum,耗时:${System.currentTimeMillis() - startTime}") } } private suspend fun getDataA(): Int { delay(1000) return 1 } private suspend fun getDataB(): Int { delay(2000) return 2 }
private fun parallelExecution(){ lifecycleScope.launch { val startTime = System.currentTimeMillis() val a = lifecycleScope.async { getDataA() } val b = lifecycleScope.async { getDataB() } val sum = a.await() + b.await() //D/MainActivity: parallelExecution: sum = 3,耗时:2009 Log.d(TAG, "parallelExecution: sum = $sum,耗时:${System.currentTimeMillis() - startTime}") } } private suspend fun getDataA(): Int { delay(1000) return 1 } private suspend fun getDataB(): Int { delay(2000) return 2 }