SingleTaskPool单线程单任务--线程池工具类

前言:单线程单任务,后提交的任务会挤掉前面的任务

/**
 * @desc
 * @auth 方毅超
 * @time 2017/8/4 16:41
 * 单线程单任务,后提交的任务会挤掉前面的任务
 */
public class SingleTaskPool {
    private static ThreadPoolExecutor pool = null;

    /*初始化线程池*/
    public static void init() {
        if (pool == null) {
            // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE),"线程池"的阻塞队列容量为1(CAPACITY)。
            pool = new ThreadPoolExecutor(1, 1, 20L, TimeUnit.SECONDS,
                    new ArrayBlockingQueue(1));
            // 设置线程池的拒绝策略为"DiscardOldestPolicy",当有任务添加到线程池被拒绝时,线程池会丢弃阻塞队列中末尾的任务,然后将被拒绝的任务添加到末尾
            // 因为阻塞队列中只能有一个任务存在,所以后提交的任务会直接替换掉当前正在等待的队列
            pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        }
    }

    /*提交任务执行*/
    public static void execute(Runnable r) {
        init();
        pool.execute(r);
    }

    /* 关闭线程池*/
    public static void unInit() {
        if (pool == null || pool.isShutdown()) return;
        pool.shutdownNow();
        pool = null;
    }

}

引用

/**
     * @auth fangyc
     * @desc 设置‘常用事务’的模块顺序
     */
    public void setModuleOrder() {
        SingleTaskPool.execute(new Runnable() {
            public void run() {
                SharedPreferences sp = context.getSharedPreferences("ModuleOrder", Context.MODE_PRIVATE); // 私有数据
                Editor editor = sp.edit();// 获取编辑器
                editor.clear();
                editor.commit();
                int size = modules.size();
                for (int i = 0; i < size; i++) {
                    LogUtil.d("DragAdapter2", "setModuleOrder==>" + modules.get(i).getIdentifier() + ":i");
                    editor.putInt(modules.get(i).getIdentifier(), i);
                }
                editor.commit();// 提交修改

                //防止程序随时被终结,所以在此实时将数据保存到json中
                CubeApplication application = CubeApplication.getInstance(context);
                application.save(application);
            }
        });

    }

 SingleTaskPool.unInit();//关闭线程池

你可能感兴趣的:(SingleTaskPool单线程单任务--线程池工具类)