默認(rèn)有4個(gè):
- 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
Unconfineddispatcher 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的實(shí)現(xiàn)跟AsyncTask的線程池比較像。IO可以創(chuàng)建很多線程池。Unconfined就是沒(méi)有指定Dispatcher,應(yīng)該盡量避免使用。
Coroutine內(nèi)部實(shí)現(xiàn)可以調(diào)用CoroutineDispatcher的dispatch方法進(jìn)行線程切換。dispatch方法可以使用Android的handler(主線程)/Java的BlockingQueue(IO線程池/Default線程池)等來(lái)實(shí)現(xiàn)。
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/dispatch.html