GlobalScope.launch
-
使用(代码会在当前线程所有内容执行完成之后再执行)
//新建线程,执行 "延时 1 秒,打印当前线程名称" 的代码
GlobalScope.launch{
delay(1000)
Log.d(TAG, "createCoroutinesOne: ${Thread.currentThread().name}")
}
//在主线程中执行 "延时 1 秒,打印当前线程名称" 的代码
GlobalScope.launch(Dispatchers.Main){
delay(1000)
Log.d(TAG, "createCoroutinesOne2: ${Thread.currentThread().name}")
}
//新建线程,执行 "延时 1 秒,打印当前线程名称" 的代码,在调用后,直接执行
GlobalScope.launch(newSingleThreadContext("bin"), CoroutineStart.DEFAULT){
delay(1000)
Log.d(TAG, "createCoroutinesOne4: ${Thread.currentThread().name}")
}
-
参数
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
...
}
- context: CoroutineContext
协程调度器 - start: CoroutineStart
协程的启动模式 - block: suspend CoroutineScope.()
执行内容
runBlocking
-
使用(代码会在调用位置直接执行。runBlocking 作用域内 launch 启动的代码,会在runBlocking 代码块其他代码执行完之后继续执行)
runBlocking {
delay(1000)
Log.d(TAG, "createCoroutinesTwo3: ${Thread.currentThread().name}")
}
runBlocking{
launch {
delay(1000)
Log.d(TAG, "createCoroutinesTwo: ${Thread.currentThread().name}")
}
Log.d(TAG, "createCoroutinesTwo2: ${Thread.currentThread().name}")
}
-
参数
public fun <T> runBlocking(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> T): T {
...
}
-
context: CoroutineContext = EmptyCoroutineContext
协程调度器
-
block: suspend CoroutineScope.()
执行内容
Dispatchers(协程调度器)
- Dispatchers.Default
在线程池中执行。适合CPU密集型的任务,比如解析JSON文件,排序一个较大的list - Dispatchers.Main
表示主线程 - Dispatchers.IO
在线程池中执行。针对磁盘和网络IO进行了优化,适合IO密集型的任务,比如:读写文件,操作数据库以及网络请求 - Dispatchers.Unconfined
在调用的线程直接执行 - newSingleThreadContext(name: String)
使用新的线程
CoroutineStart(启动模式)
- CoroutineStart.DEFAULT
默认,不传或传入此参数会立即执行协程 - CoroutineStart.LAZY
launch后不立即执行,需要获取其job发起执行 - CoroutineStart.UNDISPATCHED
在协程代码块中优先级更高,更快执行 - CoroutineStart.ATOMIC
执行前不可取消的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)