Android AsyncTask 原理及Java多線程探索
一 Java 線程
Thread
在Java 中最常見的起線程的方式,new Thread 然后重寫run 方法碳褒。新線程的函數(shù)執(zhí)行的代碼就是run函數(shù)折砸。
new Thread(){
@Override
public void run() {
System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || Hello this is Thread");
super.run();
}
}.start();
Runnable
第二種方式就是new Runable,看下Thread的run函數(shù)沙峻,這里判斷了target 是否為空睦授,target 類型為Runnable ,就是我們傳遞的參數(shù)摔寨,如果不為空去枷,執(zhí)行Runnable的Run 函數(shù)。所以在Thread中一共執(zhí)行了兩個Run函數(shù)是复,Thread.run and Runnable.run删顶。
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Time:" + System.currentTimeMillis() + " Thread:" + Thread.currentThread().getName()
+ " || Hello this is Runnable");
}
}, "RunnableThread").start();
Thread的run函數(shù):
public void run() {
if (target != null) {
target.run();
}
}
Callable and FutureTask
第三種方式是Callable 方式,是Java 為了簡化并發(fā)二提供的API淑廊《河啵看下類圖的繼承關(guān)系:
FutureTask 繼承了 RunnableFuture 接口,而RunnableFuture接口繼承了Runnable 和Future接口季惩。所以FutureTask 可以作為Runnable類型傳遞給Thread录粱。同時FutureTask內(nèi)部持有一個Callable類型的變量,Callable 有返回值蜀备,F(xiàn)utureTask和Runnable不同的是可以有返回值关摇。
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || Hello this is Callable");
return "Callable";
}
};
final FutureTask<String> futureTask= new FutureTask<String>(callable);
new Thread(futureTask, "FutureTaskThread").start();
try {
String result = futureTask.get();
System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || " + result );
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
從運(yùn)行日志上看,主線程在futureTask.get()阻塞等待 futureTask run 結(jié)束碾阁。
Time:1479020490215 Thread:Thread-0 || Hello this is Thread
Time:1479020490215 Thread:RunnableThread || Hello this is Runnable
Time:1479020495221 Thread:FutureTaskThread || Hello this is Callable
Time:1479020495221 Thread:main || Callable
FutureTask 重寫了Runnable的Run函數(shù)输虱,看下代碼的實(shí)現(xiàn),在FutureTask的run函數(shù)中調(diào)用了Callable 類型的call脂凶。
- !UNSAFE.compareAndSwapObject(this, runnerOffset,null,Thread.currentThread()))宪睹,保存Thread的句柄。這個可以通過FutureTask控制線程蚕钦。
- 調(diào)用Callable#call函數(shù)亭病。
- set(result);保存返回結(jié)果。在調(diào)用線程中可以使用get獲取返回結(jié)果嘶居。
- sun.misc.unsafe類的使用 http://blog.csdn.net/fenglibing/article/details/17138079
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
二 線程池
前面創(chuàng)建線程每次都是一個罪帖,管理起來也比較麻煩促煮,線程池是為了避免重復(fù)的創(chuàng)建Thread對象,避免過多消耗資源整袁,同時也能方便的線程的管理菠齿。主要有以下幾種類型。
- 固定線程池 Executors.newFixedThreadPool();
- 可變線程池 Executors.newCachedThreadPool();
- 單任務(wù)線程池 Executors.newSingleThreadExecutor();
- 延遲線程池 Executors.newScheduledThreadPool();
線程池和Callable 結(jié)合使用:
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> future1 = pool.submit(callable);
Future<String> future2 = pool.submit(callable);
try {
String result1 = future1.get();
System.out.println("Time:" + System.currentTimeMillis() + " Thread future1:"+ Thread.currentThread().getName() + " || " + result1);
String result2 = future2.get();
System.out.println("Time:" + System.currentTimeMillis() + " Thread future2:"+ Thread.currentThread().getName() + " || " + result2);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Executors.newFixedThreadPool(2)的日志:
可以看出兩個線程并發(fā)執(zhí)行:
Time:1479020495221 Thread:main || Callable
Time:1479020500228 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020500228 Thread:pool-1-thread-2 || Hello this is Callable
Time:1479020500229 Thread future1:main || Callable
Time:1479020500229 Thread future2:main || Callable
修改為Executors.newFixedThreadPool(1)
由于為一個線程坐昙,變成串行模式:
Time:1479020696436 Thread:main || Callable
Time:1479020701444 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020701444 Thread future1:main || Callable
Time:1479020706449 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020706450 Thread future2:main || Callable
線程池的詳細(xì)使用參考:
三 Android AsyncTask
AsyncTask 的簡單使用
AsyncTask 為一個泛型抽象類绳匀,定義如下:
public abstract class AsyncTask<Params, Progress, Result>
- Params:表示輸入的參數(shù)類型,在execute doInBackground參數(shù)類型炸客。
- Progress:進(jìn)度條參數(shù)類型疾棵,publishProgress參數(shù)類型。
- Result:結(jié)果參數(shù)類型痹仙,onPostExecute參數(shù)類型
其中doInBackground 在后臺新的線程中調(diào)用是尔,onPostExecute在主線程中調(diào)用。使用的時候調(diào)用execute蝶溶。
new HttpPostAsyncTask(this.getApplicationContext(), code).execute(URL);
public class HttpPostAsyncTask extends AsyncTask<String, Integer, String> {
private final static String TAG = "HttpTask";
public final String mUrl = "http://www.weather.com.cn/data/cityinfo/";
private Context mContext;
private String mCode;
public HttpPostAsyncTask(Context context, String code){
mContext = context;
mCode = code;
}
@Override
protected String doInBackground(String... params) {
String httpurl = mUrl+"/"+mCode+".html";
String strResult = null;
try {
HttpGet httpGet = new HttpGet(httpurl);
Log.d(TAG, "url:"+httpurl);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
Log.e(TAG, "httpResponse:"+httpResponse.toString());
strResult = EntityUtils.toString(httpResponse.getEntity());
WeatherProvider.insertWeatherInfo(strResult);
}
} catch (Exception ex) {
ex.printStackTrace();
strResult = ex.toString();
}
return strResult;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
WeatherProvider.insertWeatherInfo(result);
Intent intent = new Intent(UpdateService.updateSuccessIntent);
mContext.sendBroadcast(intent);
}
}
AsyncTask 的原理
兩板斧
看下AsyncTask 的構(gòu)造函數(shù),(7.0代碼)在構(gòu)造函數(shù)中new了WorkerRunnable嗜历, WorkerRunnable 繼承自Callable, 重新了Call函數(shù),在Call函數(shù)中調(diào)用了doInBackground,函數(shù)抖所,怎么實(shí)現(xiàn)的新線程好像已經(jīng)呼之欲出了梨州。按照套路,mFuture = new FutureTask 并且以new的WorkerRunnable mWorker為參數(shù)田轧。下面要做的就是把mFuture 提交給線程池暴匠。
在這里完成了兩板斧:
- mWorker = new WorkerRunnable ,在mWorker中調(diào)動doInBackground傻粘。
- mFuture = new FutureTask
- This constructor must be invoked on the UI thread每窖,這個是為什么?
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(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);
}
}
};
}
第三板斧
AsyncTask 執(zhí)行的時候要調(diào)用 execute. 最終調(diào)用exec.execute(mFuture);
在上面線程池的測試中調(diào)用的是ExecutorService 的submit 接口弦悉,在這里使用的是execute窒典。
二者的區(qū)別是 submit 有返回值,返回值為 Future類型稽莉,這樣可以通過get接口獲取執(zhí)行結(jié)果瀑志。
execute 無返回值。那如何獲取返回值污秆。如果是submit 接口劈猪,如果多個線程執(zhí)行,在主線程中只能依次獲取返回結(jié)果良拼,而多個返回結(jié)果的次序和時間并不確定战得,就會造成主線程阻塞。Android 的Thread Handler 模型需要出廠了庸推,Android 的編程思想是不是很強(qiáng)大常侦,Java 的線程池技術(shù)雖然解決了線程的復(fù)用 管理問題浇冰,可是沒有解決線程的執(zhí)行結(jié)果訪問的問題。在FutureTask 的run 函數(shù)中會調(diào)用set 函數(shù)保存返回結(jié)果聋亡。set函數(shù)會調(diào)用done() 函數(shù)湖饱。看下AsyncTask 的構(gòu)造函數(shù)中new FutureTask的時候重新實(shí)現(xiàn)的done()函數(shù)杀捻。done->postResultIfNotInvoked->postResult,
在postResult中首先通過
- Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
構(gòu)造了通過參數(shù)為AsyncTaskResult的message - 然后 Handler message.sendToTarget 通知主線程。
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
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;
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
結(jié)果已經(jīng)有了蚓庭,那怎么處理呢.getHandler 獲取的Handler. Handler是和主線程關(guān)聯(lián)的致讥。onProgressUpdate onPostExecute出場了,在主線程中調(diào)用器赞。
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:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
線程池的問題
在Android 的歷史上AsyncTask 修改過多次垢袱,主要是線程的數(shù)量和并發(fā)的問題。又有CPU的核數(shù)是固定的港柜,太多的線程反而會造成效率的地下请契,因此在新的版本上線程最大為:核數(shù)*2 +1。從SerialExecutor的實(shí)現(xiàn)看夏醉,AsyncTask 默認(rèn)執(zhí)行為串行爽锥。
不過Google 給我們提供了可以修改為并行的API:executeOnExecutor(Executor exec,Params... params) 自定義Executor。
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
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();
}
}
主線程調(diào)用的問題
在構(gòu)造函數(shù)的注釋中看到不能再非UI線程中調(diào)用AsyncTask.發(fā)做個測試畔柔,測試環(huán)境為 API 24 模擬器:
final String code = intent.getStringExtra("citycode");
new Thread(){
@Override
public void run(){
new HttpPostAsyncTask(UpdateService.this.getApplicationContext(), code).execute("");
}
}.start();
No Problem. 一切正常氯夷。原因可能是和Handler 有關(guān),在API24 版本中Handler 獲取的是主線程的Handler, 這樣在onPostExecute 執(zhí)行UI操作的時候就不會有問題靶擦。在老的版本上獲取Handler 可能方式不一樣腮考,獲取的調(diào)用線程的Handler. 沒有比較舊的代碼,手頭沒有代碼不能確認(rèn)玄捕。