模式 功能
DEFAULT 立即执行协程体
ATOMIC 立即执行协程体,但在开始运行之前无法取消
UNDISPATCHED 立即在当前线程执行协程体,直到第一个 suspend 调用
LAZY 只有在需要的情况下运行

DEFAULT

默认启动一个新线程,类似于线程池

  1. GlobalScope.launch() {
  2. println("1 ${Thread.currentThread()}")
  3. val job = GlobalScope.launch(start = CoroutineStart.DEFAULT) {
  4. println("2 ${Thread.currentThread()}")
  5. }
  6. delay(100)
  7. println("3 ${Thread.currentThread()}")
  8. job.join()
  9. println("4 ${Thread.currentThread()}")
  10. }
  11. Thread.sleep(1000)
  12. }

运行结果

1  Thread[DefaultDispatcher-worker-1 @coroutine#1,5,main]
2  Thread[DefaultDispatcher-worker-2 @coroutine#2,5,main]
3  Thread[DefaultDispatcher-worker-1 @coroutine#1,5,main]
4  Thread[DefaultDispatcher-worker-1 @coroutine#1,5,main]

LAZY