AsyncTask作用
異步通知,子線程在后臺(tái)運(yùn)算,進(jìn)度實(shí)時(shí)回傳(回傳到主線程還是其他線程就不一定了)
AsyncTask原理
1,AsyncTask是一個(gè)抽象類,我們看看都有什么抽象方法
protected abstract Result doInBackground(Params... params);
只有一個(gè)用于執(zhí)行在子線程的方法
2,然后是創(chuàng)建AsyncTask對(duì)象
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,創(chuàng)建一個(gè)的mHandler對(duì)象,這個(gè)不一定是主線程,Looper不為空也可以在子線程
2,創(chuàng)建一個(gè)WorkerRunnable對(duì)象mWorker
3,創(chuàng)建一個(gè)FutureTask對(duì)象mFuture
3,初始化需要準(zhǔn)備的對(duì)象后調(diào)用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;
}
我們看到執(zhí)行方法最后都是調(diào)用sDefaultExecutor來(lái)執(zhí)行,我們看一下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);
}
}
}
實(shí)現(xiàn)Executor接口,在內(nèi)部實(shí)現(xiàn)了一個(gè)隊(duì)列用于處理傳遞進(jìn)來(lái)的方法,在執(zhí)行時(shí)添加到隊(duì)列,然后在從隊(duì)里中取出要執(zhí)行的Runnable,使用THREAD_POOL_EXECUTOR執(zhí)行,繼續(xù)看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;
}
在靜態(tài)代碼塊中初始化了一個(gè)ThreadPoolExecutor線程池,然后在賦值給THREAD_POOL_EXECUTOR,到這里我們就知道了整個(gè)流程是如下
1,復(fù)寫需要執(zhí)行的方法
2,執(zhí)行方法execute,將要執(zhí)行的方法傳遞給上游的隊(duì)列
3,從上游的隊(duì)里中取出要執(zhí)行的runnable給下游線程池執(zhí)行
4,doInBackground是在線程池中執(zhí)行,其他方法都是在AsyncTask創(chuàng)建線程中調(diào)用
AsyncTask使用
寫一個(gè)類繼承自AsyncTask,復(fù)寫doInBackground方法,這個(gè)會(huì)執(zhí)行在子線程
onPreExecute會(huì)在doInBackground之前執(zhí)行
onPostExecute會(huì)在doInBackground之后執(zhí)行
onProgressUpdate進(jìn)度的回調(diào)
onCancelled cancel方法之后執(zhí)行
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);//提交之后,會(huì)執(zhí)行onProcessUpdate方法
}
return "over";
}
//在doInBackground前執(zhí)行
@Override
protected void onPreExecute() {
super.onPreExecute();
LogUtils.log("onPreExecute");
LogUtils.log(Thread.currentThread().getName());
}
//doInBackground后執(zhí)行
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
LogUtils.log("onPostExecute = " + s);
LogUtils.log(Thread.currentThread().getName());
}
//進(jìn)度回調(diào)
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
LogUtils.log("onProgressUpdate =" + values[0]);
LogUtils.log(Thread.currentThread().getName());
}
//執(zhí)行cancel方法后執(zhí)行
@Override
protected void onCancelled() {
super.onCancelled();
LogUtils.log("onCancelled");
LogUtils.log(Thread.currentThread().getName());
}
}
AsyncTask演進(jìn)
AsyncTask經(jīng)歷過(guò)串行->并行(2.3)->串行+并行(3.0)