android 处理异:AsyncTask
new MyAysnTask("AysnTask-1").execute("");
如何实现的就不写了,自行百度,下面来看一下execute方法:
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
可见execute里面又调用了executeOnExecutor(),这个是方法是通过一个线程池来执行,sDefaultExecutor是AsyncTask一个默认的线程池:串行线程池类
private static final int CPU_COUNT =
Runtime.getRuntime().availableProcessors();
//至少2个线程和最多4个线程在核心池中
// 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;
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;//默认线程池
}
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(E e) 在队列尾部添加一个元素,并返回是否成功
mTasks.offer(new Runnable() {
public void run() {
try {
//等待执行
r.run();
} finally {
//执行下一个调度线程,这样在一个队列中就实现了串行调度
scheduleNext();
}
}
});
//首次执行
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//poll() 删除队列中第一个元素,并返回该元素的值,如果元素为null,
//将返回null(其实调用的是pollFirst())
if ((mActive = mTasks.poll()) != null) {
//取一个任务。不为空就执行。
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
那么executeOnExecutor方法如下:
@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;
}
没完。。。。。。。。。。。。。。。。
网友评论