從今天開始,陸續更新我在面試過程中的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);
}