一、ThreadPoolExecutor工具类
/**
* 线程池代理类
*/
public class ThreadPoolProxy {
ThreadPoolExecutor mThreadPoolExecutor;
private int corePoolSize;
private int maximumPoolSize;
private long keepAliveTime;
public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = keepAliveTime;
}
private ThreadPoolExecutor initExecutor() {
if (mThreadPoolExecutor == null) {
synchronized (ThreadPoolProxy.class) {
if (mThreadPoolExecutor == null) {
TimeUnit unit = TimeUnit.MILLISECONDS;
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
mThreadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,//核心线程数
maximumPoolSize,//最大线程数
keepAliveTime,//保持时间
unit,//保持时间对应的单位
workQueue,
threadFactory,//线程工厂
handler);//异常捕获器
}
}
}
return mThreadPoolExecutor;
}
/**
* 执行任务
* 如果多次执行同一个runnable,会同时开启多个线程一起运行
*/
public void executeTask(Runnable r) {
initExecutor();
mThreadPoolExecutor.execute(r);
}
/**
* 提交任务
*/
public Future<?> commitTask(Runnable r) {
initExecutor();
return mThreadPoolExecutor.submit(r);
}
/**
* 删除任务(只能移除未开始的任务)
* 如果任务已经开始运行了,执行该方法会无效
*/
public void removeTask(Runnable r) {
initExecutor();
mThreadPoolExecutor.remove(r);
}
}
用法
1、创建线程池代理类和runnable对象
private ThreadPoolProxy threadPoolProxy = new ThreadPoolProxy(1, 1, 3000);
private Runnable runnable = new Runnable() {
@Override
public void run() {
//TODO
}
};
2、操作runnable对象
threadPoolProxy.executeTask(runnable);
threadPoolProxy.removeTask(runnable);
二、AsyncTask扩展
背景:多图上传,删除已选或者重新添加上传图片时
目标:取消正在运行的UploadTask ,并重新开启一个UploadTask
1、创建一个普通的Task
public class UploadTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//TODO
}
}
2、实例化对象,封装开始上传和停止上传的两个方法
private UploadTask task;
public void runUploadTask() {
if (task == null) {
task = new UploadTask ();
}
//如果之前task不为null正在运行,这里调用就会报错
task.execute();
}
public void cancleUploadTask() {
//需要考虑到的是这里的Status的两个状态
//一个是AsyncTask.Status.RUNNING,如果是这个状态就需要调用task.cancel(true)
//另一个是AsyncTask.Status.FINISHED,代表任务已经完成了
if (task != null && !task.isCancelled()) {
if (task.getStatus() == AsyncTask.Status.RUNNING) {
task.cancel(true);
}
}
task = null;
}
3、最好在Activity的onDestory()方法调用一下cancleUploadTask()
@Override
protected void onDestroy() {
super.onDestroy();
cancleUploadTask();
}