<<Android 開發(fā)藝術(shù)探索>> Chapter 11

Android的線程和線程池

主線程和子線程

  • Android中的主線程也叫UI線程,主要作用是運行四大組件以及處理他們和用戶的交互。
  • Android中的子線程的作用是執(zhí)行耗時任務(wù), 比如網(wǎng)絡(luò)請求,I/O操作等。

Android中的線程狀態(tài)

除了傳統(tǒng)的Thread外,還包含AsyncTaskHandlerThread,IntentService。

1. AsyncTask

AsyncTask其實是封裝了HandlerThread, 方便了我們的使用。

  1. AsynTask是一個抽象的泛型類,它提供了Params,ProgressResult這三個泛型參數(shù),其中

    • Params表示參數(shù)類型,
    • Progress表示后臺任務(wù)的執(zhí)行進(jìn)度的類型,
    • Result則表示后臺返回結(jié)果
  2. AsyncTask提供了4個核心方法,含義如下

    • onPreExecute()在主線程中執(zhí)行,在異步任務(wù)執(zhí)行之前,此方法會被調(diào)用
    • doInBackground(Parms… params)在線程池中執(zhí)行,此方法用于執(zhí)行異步任務(wù),params參數(shù)表示異步任務(wù)的輸入?yún)?shù)
    • onProgressUpdate(Progress… values)在主線程中執(zhí)行,當(dāng)后臺任務(wù)的執(zhí)行進(jìn)度發(fā)生改變時此方法會被調(diào)用
    • onPostExecute(Result result)在主線程中執(zhí)行,在異步任務(wù)執(zhí)行之后,此方法會被調(diào)用,其中result參數(shù)是后臺任務(wù)的返回值.

    執(zhí)行的順序是onPreExecute()先執(zhí)行,接著是doInBackground(),最后才是onPostExecute()。
    PS:(有種情況是AsyncTask()還提供了onCancelled()方法,它同樣在主線程中執(zhí)行,當(dāng)異步任務(wù)取消時,onCancelled()方法會被調(diào)用,這個時候onPostExecute()則不會被調(diào)用)

  3. AsyncTask具體有幾點限制

    • AsyncTask第一次訪問必須在主線程中加載,在android4.1及以上版本中已經(jīng)被系統(tǒng)自動完成,和在android5.0源碼中可以看出,在ActivityThreadmain()方法,它會調(diào)用AsyncTaskinit()方法,滿足了在主線程中加載的條件。
    • AsyncTask的對象必須在主線程中創(chuàng)建
    • execute必須在UI線程調(diào)用(因為excute()方法中會調(diào)用onPreExecute())
    • 一個AsyncTask對象只能執(zhí)行一次,即只能調(diào)用一次execute方法
    • 在Android1.6以前,AsyncTask是串行執(zhí)行的,Android1.6的時候開始采用并行執(zhí)行的方式,但是從Android3.0開始,為了避免AsyncTask所帶來的兵法錯誤,AsyncTask又采用一個線程來串行執(zhí)行任務(wù)。盡管如此,我們還是通過executeOnExecutor()方法來并發(fā)的執(zhí)行任務(wù)。
2. HandlerThread

HandlerThread繼承了Thread,在其run方法中通過Looper.prepare()方法來創(chuàng)建消息隊列,并通過Looper.loop()來開啟消息循環(huán),這樣在實際的使用中就允許在HandlerThread中創(chuàng)建Handler了。在不需要使用HandlerThread時,可以通過他的quit或者quitSafely方法來終止線程的執(zhí)行

// HandlerThread run()方法
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

//使用方法
HandlerThread handlerThread = new HandlerThread("MyHandler");
handlerThread.start();
Handler customHandler = new Handler(handlerThread.getLooper()){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // 處理Message
    }
};
3. IntentService
  • IntentService是服務(wù)的原因,這導(dǎo)致它的優(yōu)先級比單純的線程要高很多。其中它封裝了HandlerThreadHandler.
  • 它第一次啟動會在OnCreate方法中創(chuàng)建一個HandlerThread, 并在其中構(gòu)造了一個mServiceHandler。由于mServiceHandler發(fā)送的消息都在HandlerThread中,所以IntentService也可以執(zhí)行后臺任務(wù)。之后,mServiceHandler收到消息 后,會將Intent對象傳遞給onHandleIntent方法去處理。一般來說停止一個該服務(wù)用stopSelf(int startId),是因為stopSelf(int startId)會等到所有的消息都處理完畢后才終止服務(wù)。
  • 它也是順序執(zhí)行后臺任務(wù)。
private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        onHandleIntent((Intent)msg.obj);
        stopSelf(msg.arg1);
    }
}

@Override
public void onCreate() {
    super.onCreate();
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public void onStart(@Nullable Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}

Android中的線程池

使用線程池有以下好處:
  • 重用線程池中的線程,避免因為線程的創(chuàng)建和銷毀所帶來的性能開銷
  • 能有效控制線程池的最大并發(fā)數(shù),避免大量的線程之間因互相搶占資源而導(dǎo)致的阻塞現(xiàn)象
  • 能夠?qū)€程進(jìn)行簡單的管理,并提供定時執(zhí)行以及指定間隔循環(huán)執(zhí)行等功能

Andorid中的線程池都是直接或者間接通過配置ThreadPoolExecutor來實現(xiàn)的

public ThreadPoolExecutor(int corePoolSize,
                        int maximumPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        ThreadFactory threadFactory)
  • corePoolSize: 線程池的核心線程數(shù),默認(rèn)情況下,核心線程會在線程池中一直存活,即使他們處于閑置狀態(tài)(如果將ThreadPoolExecutorallowCoreThreadTimeOut參數(shù)設(shè)為true,那么閑置的核心線程也會受keepAliveTime參數(shù)影響被回收)
  • maximumPoolSize:線程池所能容納的最大線程數(shù),當(dāng)活動線程數(shù)達(dá)到這個數(shù)值后,后續(xù)的新任務(wù)將會被阻塞。
  • keepAliveTime:非核心線程閑置時的超時時長,超過這個時長,非核心線程就會回收。
  • unit:用于指定keepAliveTime參數(shù)的時間單位
  • workQueue:線程池中的任務(wù)隊列,通過線程池的execute方法提交的Runnable獨享會存儲在這個參數(shù)中
  • threadFactory:線程工廠,為線程池提供創(chuàng)建新線程的功能

ThreadPoolExecutor執(zhí)行任務(wù)時大致遵循如下規(guī)則:

  1. 如果線程池中的線程數(shù)量未達(dá)到核心線程的數(shù)量,那么會直接啟動一個核心線程來執(zhí)行任務(wù)。
  2. 如果線程池中的線程數(shù)量已經(jīng)達(dá)到或者超過核心線程的數(shù)量,那么任務(wù)會被插入到任務(wù)隊列中排隊等待執(zhí)行。
  3. 如果在步驟2中無法將任務(wù)插入到任務(wù)隊列中,這往往是由于任務(wù)隊列已滿,這個時候如果線程數(shù)量未達(dá)到線程池規(guī)定的最大值,那么會立刻啟動一個非核心線程來執(zhí)行任務(wù)。
  4. 如果步驟3中線程數(shù)量已經(jīng)達(dá)到線程池規(guī)定的最大值,那么就拒絕執(zhí)行此任務(wù),ThreadPoolExecutor會調(diào)用RejectedExecutionHandlerrejectedExecution方法來通知調(diào)用者。

AsyncTaskTHREAD_POOL_EXECUTOR線程池(執(zhí)行任務(wù)的線程池)的配置:

  • corePoolSize = CPU核心數(shù)+1;
  • maximumPoolSize = 2倍的CPU核心數(shù)+1;
  • 核心線程無超時機(jī)制,非核心線程在閑置時間的超時時間為1s;
  • 任務(wù)隊列的容量為128。
線程池的分類:
  • FixedThreadPool
    線程數(shù)量固定的線程池,它只有核心線程并且這些核心線程不會被回收,能夠更快地響應(yīng)外界的請求。
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(
        nThread, nThread, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()
    );
}
  • CachedThreadPool
    線程數(shù)量不固定的線程池,它只有非核心線程,比較適合執(zhí)行大量的耗時較少的任務(wù)。
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(
        0L, Interger.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()
    );
}
  • ScheduledThreadPool
    核心線程數(shù)量固定,非核心線程數(shù)量沒有限制的線程池,主要用于執(zhí)行定時任務(wù)和具有固定周期的重復(fù)任務(wù)。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Interger.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
}
  • SingleThreadExecutor
    只有一個核心線程的線程池,確保了所有的任務(wù)都在同一個線程中按順序執(zhí)行。
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService(
        new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())
    );
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容