从今天开始,陆续更新我在面试过程中的Q&A,欢迎交流。
一、 AsyncTask谈谈你的对其的理解。
AsyncTask这个类能够使用在UI线程当中,执行后台操作并能发布结果。他并不是一个android专门的线程框架,使用它的时候最好是用来处理耗时几秒的操作,如果需要线程保持长时间运行,官方建议使用其他的api。
记住3类型param progress result;四步骤 onPreExecute doInBackground onProgressUpdata onPostExecute
他的一般使用方法是通过AsyncTask的subClass overide doing background Or add second one onPostExecute
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
还有几个比较重要的点
/**AsyncTask有一个长度为128的线程池,也就是说你的Task不能多于128,一旦多于128呐肯定会宝异常了 */
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
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
*一个Executor可以被序列串的执行任务,这个序列时全局的特殊处理器?
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
/**默认情况下系统使用的是序列串的执行器,也就是说默认串 序列化执行 */
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
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();
}
}
/**新版本中这里直接掉用 THREAD_POOL_EXECUTOR.execute() ....fuck a dog*/
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* Convenience version of {@link #execute(Object...)} for use with
* a simple Runnable object. See {@link #execute(Object[])} for more
* information on the order of execution.
* 我们可以调用 比较简单的方法execute( 传个runnable接口进来),注意这里默认用的是serialExecutor
* 在老版本这意味着还是要排队的,等其他人执行完 序列化排队执行嘛~~~,在新版本中注意时掉用
* threadPoolExecutor,这个事开线程并行执行的。 我今天面试就死在这里,新版本。。。。
*/
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}