如何在安卓中使用線程池(ThreadPoolExecutor)

如何在安卓中使用線程池(ThreadPoolExecutor)

標(biāo)簽(空格分隔): 翻譯計(jì)劃


原文鏈接地址:Using ThreadPoolExecutor in Android

這篇文章將會(huì)覆蓋線程池、線程池執(zhí)行者、和怎么把他們使用到安卓里面。我們將會(huì)介紹這些主題,并且會(huì)附有許多示例代碼。

線程池(Thread Pools)

一個(gè)線程池管理者一個(gè)工作線程池(線程池確定的個(gè)數(shù)取決于我們?nèi)绾螌?shí)現(xiàn)的)

一個(gè)任務(wù)隊(duì)列保持著等待的任務(wù),這些任務(wù)將會(huì)被線程池中的等待線程執(zhí)行。生產(chǎn)者把任務(wù)添加到隊(duì)列中,而工作線程作為消費(fèi)者,只要有空閑的線程準(zhǔn)備好執(zhí)行任務(wù),就從任務(wù)隊(duì)列中取出任務(wù)并且消耗掉它。

線程執(zhí)行者(ThreadPoolExecutor)

ThreadPoolExecutor則使用線程池中的一個(gè)線程來執(zhí)行給定的任務(wù)
創(chuàng)建一個(gè)線程執(zhí)行者:

 ThreadPoolExecutor executor = ThreadPoolExecutor( int corePoolSize,
        int maximumPoolSize,
        long keepAliveTime,
        TimeUnit unit,
        BlockingQueue<Runnable> workQueue
);

這些參數(shù)的含義

  • 1、corePoolSize
    • 線程池中的最小線程個(gè)數(shù),最初的線程池個(gè)數(shù)初始化是0個(gè),但是當(dāng)我們把任務(wù)添加到隊(duì)列中的時(shí)候,一個(gè)新的線程將會(huì)被創(chuàng)建,如果有空線程,但是線程數(shù)低于corePoolSize,那么新的線程將會(huì)被繼續(xù)創(chuàng)建
  • 2、maximumPoolSize
    • 線程池中允許創(chuàng)建的最大線程個(gè)數(shù),如果這個(gè)數(shù)字超過了corePolSize,并且currentPoolSize>=corePoolSize,那么只有當(dāng)隊(duì)列滿的時(shí)候才會(huì)去創(chuàng)建新的工作線程。
  • 3、keepAliveTime
    • 線程存活時(shí)間,當(dāng)線程數(shù)大于核心線程(工作線程),那么非核心線程(多于的空閑線程)將等待新的任務(wù),如果這些線程在該參數(shù)定義的時(shí)間內(nèi)沒有得到任務(wù)去執(zhí)行,將會(huì)被銷毀。
  • 4、unit
    • 線程存活時(shí)間keepAliveTime的時(shí)間單位
  • 5、workQueue
    • 工作隊(duì)列,將會(huì)持有持續(xù)運(yùn)行任務(wù),這里將會(huì)展現(xiàn)BlockingQueue

安卓和Java中為什么會(huì)用到線程池

  • 1、這是一個(gè)強(qiáng)大的任務(wù)執(zhí)行框架,支持隊(duì)列中的任務(wù)添加,任務(wù)取消和任務(wù)優(yōu)先級排序
  • 2、它可以減少線程創(chuàng)建的開銷,因?yàn)樗麜?huì)在線程池中管理所需要的線程

在安卓中使用ThreadPoolExecutor

首先,創(chuàng)建一個(gè)PriorityThreadFactory

public class PriorityThreadFactory implements ThreadFactory {

    private final int mThreadPriority;

    public PriorityThreadFactory(int threadPriority) {
        mThreadPriority = threadPriority;
    }

    @Override
    public Thread newThread(final Runnable runnable) {
        Runnable wrapperRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Process.setThreadPriority(mThreadPriority);
                } catch (Throwable t) {

                }
                runnable.run();
            }
        };
        return new Thread(wrapperRunnable);
    }

}

創(chuàng)建一個(gè)MainThreadExecutor

public class MainThreadExecutor implements Executor {

    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override
    public void execute(Runnable runnable) {
        handler.post(runnable);
    }
}

創(chuàng)建一個(gè)DefaultExecutorSupplier

/*
* Singleton class for default executor supplier
*/
public class DefaultExecutorSupplier{
    /*
    * Number of cores to decide the number of threads
    */
    public static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
    
    /*
    * thread pool executor for background tasks
    */
    private final ThreadPoolExecutor mForBackgroundTasks;
    /*
    * thread pool executor for light weight background tasks
    */
    private final ThreadPoolExecutor mForLightWeightBackgroundTasks;
    /*
    * thread pool executor for main thread tasks
    */
    private final Executor mMainThreadExecutor;
    /*
    * an instance of DefaultExecutorSupplier
    */
    private static DefaultExecutorSupplier sInstance;

    /*
    * returns the instance of DefaultExecutorSupplier
    */
    public static DefaultExecutorSupplier getInstance() {
       if (sInstance == null) {
         synchronized(DefaultExecutorSupplier.class){                                                                  
             sInstance = new DefaultExecutorSupplier();      
        }
        return sInstance;
    }

    /*
    * constructor for  DefaultExecutorSupplier
    */ 
    private DefaultExecutorSupplier() {
        
        // setting the thread factory
        ThreadFactory backgroundPriorityThreadFactory = new 
                PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND);
        
        // setting the thread pool executor for mForBackgroundTasks;
        mForBackgroundTasks = new ThreadPoolExecutor(
                NUMBER_OF_CORES * 2,
                NUMBER_OF_CORES * 2,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(),
                backgroundPriorityThreadFactory
        );
        
        // setting the thread pool executor for mForLightWeightBackgroundTasks;
        mForLightWeightBackgroundTasks = new ThreadPoolExecutor(
                NUMBER_OF_CORES * 2,
                NUMBER_OF_CORES * 2,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(),
                backgroundPriorityThreadFactory
        );
        
        // setting the thread pool executor for mMainThreadExecutor;
        mMainThreadExecutor = new MainThreadExecutor();
    }

    /*
    * returns the thread pool executor for background task
    */
    public ThreadPoolExecutor forBackgroundTasks() {
        return mForBackgroundTasks;
    }

    /*
    * returns the thread pool executor for light weight background task
    */
    public ThreadPoolExecutor forLightWeightBackgroundTasks() {
        return mForLightWeightBackgroundTasks;
    }

    /*
    * returns the thread pool executor for main thread task
    */
    public Executor forMainThreadTasks() {
        return mMainThreadExecutor;
    }
}

現(xiàn)在在你的代碼邏輯中使用吧

/*
* Using it for Background Tasks
*/
public void doSomeBackgroundWork(){
  DefaultExecutorSupplier.getInstance().forBackgroundTasks()
    .execute(new Runnable() {
    @Override
    public void run() {
       // do some background work here.
    }
  });
}

/*
* Using it for Light-Weight Background Tasks
*/
public void doSomeLightWeightBackgroundWork(){
  DefaultExecutorSupplier.getInstance().forLightWeightBackgroundTasks()
    .execute(new Runnable() {
    @Override
    public void run() {
    // do some light-weight background work here.
    }
  });
}

/*
* Using it for MainThread Tasks
*/
public void doSomeMainThreadWork(){
  DefaultExecutorSupplier.getInstance().forMainThreadTasks()
    .execute(new Runnable() {
    @Override
    public void run() {
       // do some Main Thread work here.
    }
  });
}

通過這種方式,我們可以創(chuàng)建不同的線程池來服務(wù)于網(wǎng)絡(luò)任務(wù)/IO任務(wù)/(后臺(tái))耗時(shí)任務(wù)、還有其他任務(wù)。

如何取消任務(wù)

當(dāng)我們?nèi)∠粋€(gè)任務(wù)的時(shí)候,我們需要得到一個(gè)Future,而不是直接執(zhí)行,因此我們需要使用submit,這樣將會(huì)返回一個(gè)Future,然后我們就可以使用返回回來的Future來取消任務(wù).

/*
* Get the future of the task by submitting it to the pool
*/
Future future = DefaultExecutorSupplier.getInstance().forBackgroundTasks()
    .submit(new Runnable() {
    @Override
    public void run() {
      // do some background work here.
    }
});

/*
* cancelling the task
*/
future.cancel(true); 

如何對一個(gè)任務(wù)設(shè)置優(yōu)先級

假設(shè)一個(gè)任務(wù)隊(duì)列中有20個(gè)任務(wù),而我們創(chuàng)建的線程池只有四個(gè)可用于工作的線程,我們可以基于優(yōu)先級來執(zhí)行任務(wù),畢竟我們一次只能執(zhí)行4個(gè)任務(wù)。

假設(shè)我們需要在隊(duì)列中首先執(zhí)行最后一個(gè)任務(wù),我們可以為這個(gè)線程設(shè)置IMMEDIATE優(yōu)先級,以便于我們在隊(duì)列中獲取新任務(wù)的時(shí)候,將會(huì)執(zhí)行此任務(wù)(因?yàn)檫@個(gè)標(biāo)志的任務(wù)具有最高優(yōu)先級)

要設(shè)置任務(wù)的優(yōu)先級,我們需要?jiǎng)?chuàng)建一個(gè)線程池執(zhí)行器

創(chuàng)建枚舉優(yōu)先級

/**
 * Priority levels
 */
public enum Priority {
    /**
     * NOTE: DO NOT CHANGE ORDERING OF THOSE CONSTANTS UNDER ANY CIRCUMSTANCES.
     * Doing so will make ordering incorrect.
     */

    /**
     * Lowest priority level. Used for prefetches of data.  低級優(yōu)先級
     */
    LOW,

    /**
     * Medium priority level. Used for warming of data that might soon get visible.  中端優(yōu)先級
     */
    MEDIUM,  

    /**
     * Highest priority level. Used for data that are currently visible on screen.  高優(yōu)先級
     */
    HIGH,

    /**
     * Highest priority level. Used for data that are required instantly(mainly for emergency).  最高優(yōu)先級
     */
    IMMEDIATE;
}

創(chuàng)建一個(gè)優(yōu)先級線程

public class PriorityRunnable implements Runnable {

    private final Priority priority;

    public PriorityRunnable(Priority priority) {
        this.priority = priority;
    }

    @Override
    public void run() {
      // nothing to do here.
    }

    public Priority getPriority() {
        return priority;
    }

}

創(chuàng)建一個(gè)PriorityThreadPoolExecutor(優(yōu)先級線程執(zhí)行者)繼承于ThreadPoolExecutor,我們還需要?jiǎng)?chuàng)建一個(gè)PriorityFutureTask,實(shí)現(xiàn)Comparable<PriorityFutureTask>接口

public class PriorityThreadPoolExecutor extends ThreadPoolExecutor {

   public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
         TimeUnit unit, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit,new PriorityBlockingQueue<Runnable>(), threadFactory);
    }

    @Override
    public Future<?> submit(Runnable task) {
        PriorityFutureTask futureTask = new PriorityFutureTask((PriorityRunnable) task);
        execute(futureTask);
        return futureTask;
    }

    private static final class PriorityFutureTask extends FutureTask<PriorityRunnable>
            implements Comparable<PriorityFutureTask> {
        private final PriorityRunnable priorityRunnable;

        public PriorityFutureTask(PriorityRunnable priorityRunnable) {
            super(priorityRunnable, null);
            this.priorityRunnable = priorityRunnable;
        }
        /*
         * compareTo() method is defined in interface java.lang.Comparable and it is used
         * to implement natural sorting on java classes. natural sorting means the the sort 
         * order which naturally applies on object e.g. lexical order for String, numeric 
         * order for Integer or Sorting employee by there ID etc. most of the java core 
         * classes including String and Integer implements CompareTo() method and provide
         * natural sorting.
         */
        @Override
        public int compareTo(PriorityFutureTask other) {
            Priority p1 = priorityRunnable.getPriority();
            Priority p2 = other.priorityRunnable.getPriority();
            return p2.ordinal() - p1.ordinal();
        }
    }
}

首先,在DefaultExecutorSupplier,而不是ThreadPoolExecutor中,向一下使用方式使用PriorityThreadPoolExecutor.

public class DefaultExecutorSupplier{

private final PriorityThreadPoolExecutor mForBackgroundTasks;

private DefaultExecutorSupplier() {
  
        mForBackgroundTasks = new PriorityThreadPoolExecutor(
                NUMBER_OF_CORES * 2,
                NUMBER_OF_CORES * 2,
                60L,
                TimeUnit.SECONDS,
                backgroundPriorityThreadFactory
        );

    }
}

給一個(gè)如何給一個(gè)任務(wù)設(shè)置優(yōu)先級的例子

/*
* do some task at high priority
*/
public void doSomeTaskAtHighPriority(){
  DefaultExecutorSupplier.getInstance().forBackgroundTasks()
    .submit(new PriorityRunnable(Priority.HIGH) {
    @Override
    public void run() {
      // do some background work here at high priority.
    }
});
}

通過這種方式,我們就可以創(chuàng)建一個(gè)具有優(yōu)先級的任務(wù),上述所有使用方式同樣適用于Java Applications

這里給一個(gè)我自己封裝的安卓網(wǎng)絡(luò)工作的依賴庫Android Networking Library

如果想知道更詳細(xì)的實(shí)現(xiàn),可以查看DefaultExecutorSupplier.java這個(gè)類在Android Networking here.

我希望這些知識(shí)對于你有些幫助

感謝您閱讀本文。
如果您發(fā)現(xiàn)它有用,請務(wù)必點(diǎn)擊下面的?推薦這篇文章。

如果想知道更多的關(guān)于程序設(shè)計(jì)方面的知識(shí), follow me and Mindorks ,以便于我們更新新的技術(shù)文章的時(shí)候會(huì)通知到你。

Check out all the Mindorks best articles here.

Also, Let’s become friends on Twitter, Linkedin, Github and Facebook.

當(dāng)然了最后的這些推薦都是需要翻墻的,這個(gè)就需要大家墻一下了哈.這里推薦給大家一個(gè)翻墻的網(wǎng)址,需要收費(fèi)的,但是非常便宜的(最低的套餐一個(gè)月15G/1.5元 一年才18(現(xiàn)在搞活動(dòng))),可以看一下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,001評論 6 537
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,786評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,986評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,204評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,964評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,354評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,410評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,554評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,106評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,918評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,093評論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,648評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,342評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,755評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,009評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,839評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,107評論 2 375

推薦閱讀更多精彩內(nèi)容