默认有4个:
- Dispatchers.Default — is used by all standard builders if no dispatcher or any other ContinuationInterceptor is specified in their context. It uses a common pool of shared background threads. This is an appropriate choice for compute-intensive coroutines that consume CPU resources.
- Dispatchers.IO — uses a shared pool of on-demand created threads and is designed for offloading of IO-intensive blocking operations (like file I/O and blocking socket I/O).
-
Dispatchers.Unconfined — starts coroutine execution in the current call-frame until the first suspension, whereupon the coroutine builder function returns. The coroutine will later resume in whatever thread used by the corresponding suspending function, without confining it to any specific thread or pool. The
Unconfined
dispatcher should not normally be used in code. - Dispatchers.Main A coroutine dispatcher that is confined to the Main thread operating with UI objects. Usually such dispatchers are single-threaded.
Main就是主线程。Default的实现跟AsyncTask的线程池比较像。IO可以创建很多线程池。Unconfined就是没有指定Dispatcher,应该尽量避免使用。
Coroutine内部实现可以调用CoroutineDispatcher的dispatch方法进行线程切换。dispatch方法可以使用Android的handler(主线程)/Java的BlockingQueue(IO线程池/Default线程池)等来实现。
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/dispatch.html