Android AsyncTask 原理及Java多线程探索
一 Java 线程
Thread
在Java 中最常见的起线程的方式,new Thread 然后重写run 方法。新线程的函数执行的代码就是run函数。
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函数,这里判断了target 是否为空,target 类型为Runnable ,就是我们传递的参数,如果不为空,执行Runnable的Run 函数。所以在Thread中一共执行了两个Run函数,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函数:
public void run() {
if (target != null) {
target.run();
}
}
Callable and FutureTask
第三种方式是Callable 方式,是Java 为了简化并发二提供的API。看下类图的继承关系:
FutureTask 继承了 RunnableFuture 接口,而RunnableFuture接口继承了Runnable 和Future接口。所以FutureTask 可以作为Runnable类型传递给Thread。同时FutureTask内部持有一个Callable类型的变量,Callable 有返回值,FutureTask和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();
}
从运行日志上看,主线程在futureTask.get()阻塞等待 futureTask run 结束。
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函数,看下代码的实现,在FutureTask的run函数中调用了Callable 类型的call。
- !UNSAFE.compareAndSwapObject(this, runnerOffset,null,Thread.currentThread())),保存Thread的句柄。这个可以通过FutureTask控制线程。
- 调用Callable#call函数。
- set(result);保存返回结果。在调用线程中可以使用get获取返回结果。
- 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);
}
}
二 线程池
前面创建线程每次都是一个,管理起来也比较麻烦,线程池是为了避免重复的创建Thread对象,避免过多消耗资源,同时也能方便的线程的管理。主要有以下几种类型。
- 固定线程池 Executors.newFixedThreadPool();
- 可变线程池 Executors.newCachedThreadPool();
- 单任务线程池 Executors.newSingleThreadExecutor();
- 延迟线程池 Executors.newScheduledThreadPool();
线程池和Callable 结合使用:
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)的日志:
可以看出两个线程并发执行:
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
线程池的详细使用参考:
三 Android AsyncTask
AsyncTask 的简单使用
AsyncTask 为一个泛型抽象类,定义如下:
public abstract class AsyncTask<Params, Progress, Result>
- Params:表示输入的参数类型,在execute doInBackground参数类型。
- Progress:进度条参数类型,publishProgress参数类型。
- Result:结果参数类型,onPostExecute参数类型
其中doInBackground 在后台新的线程中调用,onPostExecute在主线程中调用。使用的时候调用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 的构造函数,(7.0代码)在构造函数中new了WorkerRunnable, WorkerRunnable 继承自Callable, 重新了Call函数,在Call函数中调用了doInBackground,函数,怎么实现的新线程好像已经呼之欲出了。按照套路,mFuture = new FutureTask 并且以new的WorkerRunnable mWorker为参数。下面要做的就是把mFuture 提交给线程池。
在这里完成了两板斧:
- mWorker = new WorkerRunnable ,在mWorker中调动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 执行的时候要调用 execute. 最终调用exec.execute(mFuture);
在上面线程池的测试中调用的是ExecutorService 的submit 接口,在这里使用的是execute。
二者的区别是 submit 有返回值,返回值为 Future类型,这样可以通过get接口获取执行结果。
execute 无返回值。那如何获取返回值。如果是submit 接口,如果多个线程执行,在主线程中只能依次获取返回结果,而多个返回结果的次序和时间并不确定,就会造成主线程阻塞。Android 的Thread Handler 模型需要出厂了,Android 的编程思想是不是很强大,Java 的线程池技术虽然解决了线程的复用 管理问题,可是没有解决线程的执行结果访问的问题。在FutureTask 的run 函数中会调用set 函数保存返回结果。set函数会调用done() 函数。看下AsyncTask 的构造函数中new FutureTask的时候重新实现的done()函数。done->postResultIfNotInvoked->postResult,
在postResult中首先通过
- Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
构造了通过参数为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;
}
结果已经有了,那怎么处理呢.getHandler 获取的Handler. Handler是和主线程关联的。onProgressUpdate onPostExecute出场了,在主线程中调用。
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 修改过多次,主要是线程的数量和并发的问题。又有CPU的核数是固定的,太多的线程反而会造成效率的地下,因此在新的版本上线程最大为:核数*2 +1。从SerialExecutor的实现看,AsyncTask 默认执行为串行。
不过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();
}
}
主线程调用的问题
在构造函数的注释中看到不能再非UI线程中调用AsyncTask.发做个测试,测试环境为 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 有关,在API24 版本中Handler 获取的是主线程的Handler, 这样在onPostExecute 执行UI操作的时候就不会有问题。在老的版本上获取Handler 可能方式不一样,获取的调用线程的Handler. 没有比较旧的代码,手头没有代码不能确认。