协程(Kotlin-协程)

内容头部广告位(手机)

一、开启协程的方式

  1. 使用 runBlocking 顶层函数。它会 在协程作用域内的所有代码和子协程没有全部执行完成之前 一直阻塞当前线程。一般在测试环境中使用。

runBlocking { }

  1. 使用 GlobalScope 单例对象。也是顶层协程。不推荐使用。

GlobalScopeXX)await()) }

await()方法会阻塞当前协程,直到获取到async函数的结果。

二、Dispatchers指定线程

  1. DispatchersIO:针对磁盘和网络 IO 进行了优化,适合 IO 密集型的任务,比如:读写文件,操作数据库以及网络请求
  2. DispatchersUnconfined:不推荐使用

runBlocking { withContext(DispatchersIO){ } withContext(DispatchersIO){ } private suspend fun test(string:String) :String = withContext(DispatchersDefault)sleep(6000) println("end") } suspend fun test() { delay(3000) println("test") } 运行结果 1 test 2 end

四、子协程launch代码块

子协程launch代码块不会影响后面代码的运行(因为子协程本来就是新的协程,和原来的代码块分开各跑各的)。

fun main(arg: Array<String>) { CoroutineScope(Dispatcherslaunch { launch { // 新的子协程,不影响后面代码的运行 delay(3000) println("0") } test() println("1") } Thread") } println("main finished main finishedDefault)") } println("main finished 1 main finished.

内容底部广告位(手机)
标签:

管理员
草根站长管理员

专注网站优化+网络营销,只做有思想的高价值网站,只提供有担当的营销服务!

上一篇:临汾机场电话(临汾机场订票电话)
下一篇:花园城市(「践行嘱托三年间 信阳答卷特刊」花园城市换新貌)