xUtils 源码解析(二)

接下来我们看看task模块下有哪些类。


xUtils 源码解析(二)_第1张图片
屏幕快照 2018-01-28 14.35.02.png
  • Priority类,是一个枚举类定义了一些级别
public enum Priority {
    UI_TOP,
    UI_NORMAL,
    UI_LOW,
    DEFAULT,
    BG_TOP,
    BG_NORMAL,
    BG_LOW;
}
  • TaskHandler定义了一些接口。
public interface TaskHandler {
    boolean supportPause();
    boolean supportResume();
    boolean supportCancel();
    void pause();
    void resume();
    void cancel();
    boolean isPaused();
    boolean isCancelled();
}
  • PriorityObject,就是给一个对象加上一个优先级而已。
public class PriorityObject {

    public final Priority priority;
    public final E obj;

    public PriorityObject(Priority priority, E obj) {
        this.priority = priority == null ? Priority.DEFAULT : priority;
        this.obj = obj;
    }
}
  • PriorityRunnable 带有优先级的一个Runnable
public class PriorityRunnable extends PriorityObject implements Runnable {

    public PriorityRunnable(Priority priority, Runnable obj) {
        super(priority, obj);
    }

    @Override
    public void run() {
        this.obj.run();
    }
}
  • PriorityExecutor ,就是自定义了一个线程池


    xUtils 源码解析(二)_第2张图片
    屏幕快照 2018-01-28 14.46.57.png
public class PriorityExecutor implements Executor {
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "PriorityExecutor #" + mCount.getAndIncrement());
        }
    };

    private final BlockingQueue mPoolWorkQueue = new PriorityObjectBlockingQueue();
    private final ThreadPoolExecutor mThreadPoolExecutor;

    public PriorityExecutor() {
        this(CORE_POOL_SIZE);
    }

    public PriorityExecutor(int poolSize) {
        mThreadPoolExecutor = new ThreadPoolExecutor(
                poolSize,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE,
                TimeUnit.SECONDS,
                mPoolWorkQueue,
                sThreadFactory);
    }

    public boolean isBusy() {
        return mThreadPoolExecutor.getActiveCount() >= mThreadPoolExecutor.getCorePoolSize();
    }
}
  • PriorityAsyncTask 可以类比AsyncTask源码分析,其实就是加上了Priority属性,线程池换了PriorityExecutor,再次就不多说了。

  • PriorityObjectBlockingQueue,在xUtils3 里面将其修改为PriorityBlockingQueue。【死磕Java并发】-----J.U.C之阻塞队列:PriorityBlockingQueue,以及JUC源码分析-集合篇(七):PriorityBlockingQueue

你可能感兴趣的:(xUtils 源码解析(二))