Kotlin: 协程学习笔记

一、CoroutineScope (推荐)

    private fun testScope() {
        val coroutineScope = CoroutineScope(Dispatchers.Main)
        coroutineScope.launch(Dispatchers.IO) {
            val text = getText()
            coroutineScope.launch(Dispatchers.Main) {
                tv1.text = text
            }
        }
    }
 
    private suspend fun getText(): String {
        Thread.sleep(3000)
        return "网络数据..."
    }

二、阻塞型 runBlocking(不推荐)

这是一种不推荐的开启协程的方式,因为这种会阻塞线程。启动一个新的协程,并阻塞它的调用线程,直到里面的代码执行完毕。
其实在业务开发过程中,也没有多少这种需求需要阻塞线程的。

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coroutines)
        val startTime = System.currentTimeMillis()
        Log.d(TAG, "开始获取网络数据...time: $startTime")
        runBlocking {
            val text = getText()
            Log.d(TAG, "网络数据...$text   time: ${System.currentTimeMillis() - startTime}  currentThread:${Thread.currentThread().name}")
        }
        Log.d(TAG, "执行完毕... time: ${System.currentTimeMillis() - startTime}")
    }
 
 
    private suspend fun getText(): String {
        Thread.sleep(3000)
        return "网络数据..."
    }

看日志分析:

image.png

很明显,在主线程回调,runBlocking 阻塞了线程。这是一种不推荐开启协程的方式

其实这种方式,和不开启协程是没有去区别,因为上述功能直接写在协程外面同样阻塞主线程。

当然,runBlocking 是可以指定线程,不过同样会阻塞其依赖的线程

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容