使用(代码会在当前线程所有内容执行完成之后再执行)
//新建线程,执行 "延时 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 {
...
}
使用(代码会在调用位置直接执行。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.()
执行内容