Jetpack
下 androidx.arch.core.executor
包中有一个线程池实现类 ArchTaskExecutor
,
内部实现了切换线程的功能。
使用如下:
/**
*Author:XingHai.Zhao
*Purpose: ArchTaskExecutor实用举例
*/
Executor threadExecutor;
//处在未知线程中,判断当前线程是否是主线程,依此来决定线程要切换到哪个线程
if (Thread.currentThread() == Looper.getMainLooper().getThread()){
//这里的逻辑是:如果当前处于主线程,那么最后切换到主线程
threadExecutor = ArchTaskExecutor.getMainThreadExecutor();
}else {
threadExecutor = ArchTaskExecutor.getIOThreadExecutor();
}
thread {
//最终决定业务在哪里执行或返回
threadExecutor.execute(new Runnable() {
@Override
public void run() {
//需要最终切换的业务
}
});
}