前言:單線程單任務(wù),后提交的任務(wù)會(huì)擠掉前面的任務(wù)
/**
* @desc
* @auth 方毅超
* @time 2017/8/4 16:41
* 單線程單任務(wù),后提交的任務(wù)會(huì)擠掉前面的任務(wù)
*/
public class SingleTaskPool {
private static ThreadPoolExecutor pool = null;
/*初始化線程池*/
public static void init() {
if (pool == null) {
// 創(chuàng)建線程池。線程池的"最大池大小"和"核心池大小"都為1(THREADS_SIZE),"線程池"的阻塞隊(duì)列容量為1(CAPACITY)。
pool = new ThreadPoolExecutor(1, 1, 20L, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1));
// 設(shè)置線程池的拒絕策略為"DiscardOldestPolicy",當(dāng)有任務(wù)添加到線程池被拒絕時(shí),線程池會(huì)丟棄阻塞隊(duì)列中末尾的任務(wù),然后將被拒絕的任務(wù)添加到末尾
// 因?yàn)樽枞?duì)列中只能有一個(gè)任務(wù)存在,所以后提交的任務(wù)會(huì)直接替換掉當(dāng)前正在等待的隊(duì)列
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
}
}
/*提交任務(wù)執(zhí)行*/
public static void execute(Runnable r) {
init();
pool.execute(r);
}
/* 關(guān)閉線程池*/
public static void unInit() {
if (pool == null || pool.isShutdown()) return;
pool.shutdownNow();
pool = null;
}
}
引用
/**
* @auth fangyc
* @desc 設(shè)置‘常用事務(wù)’的模塊順序
*/
public void setModuleOrder() {
SingleTaskPool.execute(new Runnable() {
public void run() {
SharedPreferences sp = context.getSharedPreferences("ModuleOrder", Context.MODE_PRIVATE); // 私有數(shù)據(jù)
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();// 提交修改
//防止程序隨時(shí)被終結(jié),所以在此實(shí)時(shí)將數(shù)據(jù)保存到j(luò)son中
CubeApplication application = CubeApplication.getInstance(context);
application.save(application);
}
});
}
SingleTaskPool.unInit();//關(guān)閉線程池