AsyncTask作用
异步通知,子线程在后台运算,进度实时回传(回传到主线程还是其他线程就不一定了)
AsyncTask原理
1,AsyncTask是一个抽象类,我们看看都有什么抽象方法
protected abstract Result doInBackground(Params... params);
只有一个用于执行在子线程的方法
2,然后是创建AsyncTask对象
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
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 {
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
1,创建一个的mHandler对象,这个不一定是主线程,Looper不为空也可以在子线程
2,创建一个WorkerRunnable对象mWorker
3,创建一个FutureTask对象mFuture
3,初始化需要准备的对象后调用execute方法,
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
我们看到执行方法最后都是调用sDefaultExecutor来执行,我们看一下sDefaultExecutor是啥
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
实现Executor接口,在内部实现了一个队列用于处理传递进来的方法,在执行时添加到队列,然后在从队里中取出要执行的Runnable,使用THREAD_POOL_EXECUTOR执行,继续看THREAD_POOL_EXECUTOR
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
在静态代码块中初始化了一个ThreadPoolExecutor线程池,然后在赋值给THREAD_POOL_EXECUTOR,到这里我们就知道了整个流程是如下
1,复写需要执行的方法
2,执行方法execute,将要执行的方法传递给上游的队列
3,从上游的队里中取出要执行的runnable给下游线程池执行
4,doInBackground是在线程池中执行,其他方法都是在AsyncTask创建线程中调用
AsyncTask使用
写一个类继承自AsyncTask,复写doInBackground方法,这个会执行在子线程
onPreExecute会在doInBackground之前执行
onPostExecute会在doInBackground之后执行
onProgressUpdate进度的回调
onCancelled cancel方法之后执行
public class MyAynctask extends AsyncTask<String,Integer,String> {
@Override
protected String doInBackground(String... strings) {
LogUtils.log(" doInBackground=" + strings[0]);
LogUtils.log(Thread.currentThread().getName());
int times = 10;
for (int i = 0; i < times; i++) {
publishProgress(i);//提交之后,会执行onProcessUpdate方法
}
return "over";
}
//在doInBackground前执行
@Override
protected void onPreExecute() {
super.onPreExecute();
LogUtils.log("onPreExecute");
LogUtils.log(Thread.currentThread().getName());
}
//doInBackground后执行
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
LogUtils.log("onPostExecute = " + s);
LogUtils.log(Thread.currentThread().getName());
}
//进度回调
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
LogUtils.log("onProgressUpdate =" + values[0]);
LogUtils.log(Thread.currentThread().getName());
}
//执行cancel方法后执行
@Override
protected void onCancelled() {
super.onCancelled();
LogUtils.log("onCancelled");
LogUtils.log(Thread.currentThread().getName());
}
}
AsyncTask演进
AsyncTask经历过串行->并行(2.3)->串行+并行(3.0)