newFixedThreadPool(int number): 创建包含固定个数的线程池
public static ExecutorService getFixedThreadPool(){
//创建三个线程队列的方法.只能有三个线程存在,如果超过就加入队列等待执行
return Executors.newFixedThreadPool(3);
}
newCachedThreadPool() :根据实际情况调整线程的数量的线程池
/**
* 创建一个根据实际需求变化的线程池
* @return
*/
public static ExecutorService getNewCachedThreadPool(){
return Executors.newCachedThreadPool();
}
newSingleThreadExecutor() :
public static ExecutorService getNewSingleThreadPool(){
//创建只有一个线程的线程池
return Executors.newSingleThreadExecutor();
}
newScheduledThreadPool() :
ScheduledExecutorService newScheduleThreadPool = ExcutorFractory.getNewScheduleThreadPool();
//正常的调用,跟上面的一样
// newScheduleThreadPool.execute(new Runnable(){});
//延迟2秒后执行该任务
newScheduleThreadPool.schedule(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
Log.e("cai" , "当前线程:" + name + "执行的是第:" +"个任务");
}
}, 2, TimeUnit.SECONDS);
//延迟1秒后,每隔2秒执行一次该任务
newScheduleThreadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
Log.e("cai" , "当前线程:" + name + "执行的是第:" +"个任务");
}
}, 1, 2, TimeUnit.SECONDS);
newSingleThreadScheduledExecutor() :调取同上
创建一个可以定时或者周期性执行任务的线程池,该线程池的线程数为1 ;
以上方法的内部实现都是通过创建一个ThreadPoolExecutor对象来创建的:
/**
* 返回一个自定义的优先级线程池
* @return
*/
public static ExecutorService getPriorityThreadPool(){
return new ThreadPoolExecutor(3,3,0L, TimeUnit.SECONDS,
new PriorityBlockingQueue()) ;
}
/**
* 创建一个实现Runnable接口的类,并向外提供一个抽象方法供我们实现自定义功能,
* 并实现Comparable接口,实现这个接口主要就是进行优先级的比较
* Created by shiqiang on 2017/5/31.
*/
public abstract class PriorityRunnable implements Runnable , Comparable{
private int priority;
public PriorityRunnable(int priority) {
if (priority < 0 ){
throw new IllegalArgumentException();
}
this.priority = priority;
}
@Override
public void run() {
doThing();
}
protected abstract void doThing() ;
@Override
public int compareTo(@NonNull PriorityRunnable another) {
int my = this.priority;
int other = another.getPriority();
return my < other ? 1 : my > other ? -1 : 0;
}
public int getPriority() {
return priority;
}
}
//调用的方法
ExecutorService priorityThreadPool = ExcutorFractory.getPriorityThreadPool();
for (int i = 0; i < 10; i++) {
final int priory = i ;
priorityThreadPool.execute(new PriorityRunnable(priory) {
@Override
protected void doThing() {
String name = Thread.currentThread().getName();
//
Log.e("cai" , "当前线程:" + name + "执行的是第:" + priory +"个任务");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public class MyThreadPoolExecutor extends ThreadPoolExecutor {
private ReentrantLock pauseLock = new ReentrantLock();
private Condition unpaused = pauseLock.newCondition();
public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
Log.e("cai", "线程:" + t.getName() + "准备执行任务!");
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Log.e("cai", "线程:" + Thread.currentThread().getName() + "任务执行结束!!");
}
@Override
protected void terminated() {
super.terminated();
Log.e("cai", "线程结束!!");
}
}
AsyncTask和Handler对比
AsyncTask实现的原理,和适用的优缺点
在Handler 异步实现时,涉及到 Handler, Looper, Message,Thread四个对象,实现异步的流程是主线程启动Thread(子线程)àthread(子线程)运行并生成Message-àLooper获取Message并传递给HandleràHandler逐个获取Looper中的Message,并进行UI变更。
使用的优点:
使用的缺点:
AsyncTask介绍
Android的AsyncTask比Handler更轻量级一些,适用于简单的异步处理。
首先明确Android之所以有Handler和AsyncTask,都是为了不阻塞主线程(UI线程),且UI的更新只能在主线程中完成,因此异步处理是不可避免的。
AsyncTask调取excute()实际是调取executeOnExecutor()指定调取的线程池版本不同默认调取也不同现在是FatureTask中SerialExecutor(串行),以前用过并行
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
//exec是就是我们传进来的sDefaultExecutor。那么接下来我们看看sDefaultExecutor究竟是什么。在AsyncTask类的源码中
exec.execute(mFuture);
return this;
}
exec是就是我们传进来的sDefaultExecutor。那么接下来我们看看sDefaultExecutor究竟是什么。在AsyncTask类的源码中
//新建的serialExecute()线程池
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
serialExecute()线程池;
/**
参数r就是我们传入的mFuture的run方法,而mFuture的run方法内部会调用mWorker的call方法,然后就会调用doInBackground方法,我们的后台任务也就开始执行了
*/
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
//传递进来的Runable
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
r.run() -> mWorker.call()中调取doInBackgroud():@WorkerThread后台工作进程
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//如果doInbackgroud执行完毕或者暂停进程调取PostResult方法
postResult(result);
}
return result;
}
};
注意在doInBackgroud中调取publishProgress()更新数据:注意其运行在工作线程,子线程中,发送Handler给UI线程的Handler;
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult
同理4.中finally()时调取postResult(),同样是使用Handler发送一个消息给UI线程
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
AsyncTask中静态Handler();
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult> result = (AsyncTaskResult>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// 使用postResult()发送的结果数据
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//publishProgress()通知更新控件进度的
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
onProgressUpdate()更新控件在MainThread:UI线程
@MainThread
protected void onProgressUpdate(Progress... values) {
}
finish()方法:
private void finish(Result result) {
//如果在4.中的doInbackGroud中取消时候调取postResult后调取AsyncTask中的Oncancelled(),否则下载完成以后调取onPostExecute();
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
//把mStatus设为FINISHED,表示当前AsyncTask对象已经执行完毕;
mStatus = Status.FINISHED;
}