Android多線程操作——線程池管理綜述

來源:互聯網
上載者:User

標籤:


題記——

 難過了,悄悄走一走;

        傷心了,默默睡一覺;

        優雅不是訓練出來的,而是一種閱曆;

        淡然不是偽裝出來的,而是一種沉澱;


        時間飛逝,老去的只是我們的容顏;

        時間彷彿一顆靈魂,越來越動人;


1、簡述:

    在多線程的世界中,是那麼的神奇 與 高效以及合理;

2、建立線程池執行個體

    官方推薦使用Executors類Factory 方法來建立線程池管理,Executors類是官方提供的一個工廠類,裡面封裝了好多功能不一樣的線程池,從而使得我們建立線程池非常的簡單:


 
                



3、使用線程池來管理工作
              
              
                 
             
               
             


4、Executors核心建立說明


 

可以看到1 - 3 建立線程池的方法中,全部是建立了ThreadPoolExecutor這個對象執行個體,不同的只是構造中的參數不一至,而在4 與5 ,從其繼承的角度來看


public class ScheduledThreadPoolExecutor        extends ThreadPoolExecutor        implements ScheduledExecutorService {    


可以看到其實質也是繼承於ThreadPoolExecutor這個對象執行個體。

也就是說上述一種類型的線程池其都是 ThreadPoolExecutor子類,其實直接建立ThreadPoolExecutor執行個體對象,只需要傳入相對應的配製參數,就可以建立出來與上述五種效果相一至的線程池管理,只不過是在書寫的時候太過於繁鎖。

 /**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters and default thread factory and rejected execution handler.     * It may be more convenient to use one of the {@link Executors} factory     * methods instead of this general purpose constructor.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @throws IllegalArgumentException if one of the following holds:<br>     *         {@code corePoolSize < 0}<br>     *         {@code keepAliveTime < 0}<br>     *         {@code maximumPoolSize <= 0}<br>     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             Executors.defaultThreadFactory(), defaultHandler);    }


5、ThreadPoolExecutor簡述


從上述建立ThreadPoolEecutor執行個體的構造來說,


 

6、自訂線程池

    /**     * 建立線程池也是需要資源的,所以線程池內線程數量的大小也會影響系統的效能,     * 大了反而浪費資源,小了反而影響系統的輸送量,     * 所以我們建立線程池需要把握一個度才能合理的發揮它的優點,     * 通常來說我們要考慮的因素有CPU的數量、記憶體的大小、並發請求的數量等因素,按需調整。     *通常核心線程數可以設為CPU數量+1,而最大線程數可以設為CPU的數量*2+1。     */    private void customThreadFunction() {        /**         * 擷取CPU數量         */        int processors = Runtime.getRuntime().availableProcessors();        /**         * 核心線程數量         */        int corePoolSize =processors + 1;        /**         * 最大線程數量         */        int maximumPoolSize =  processors * 2 + 1;        /**         * 空閑有效時間         */        long keepAliveTime = 60;        /**         * 建立自訂線程池         */        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new PriorityBlockingQueue());        /**         * 添加執行任務         */        for (int i=1;i<=20;i++){            final int prites = i;            threadPoolExecutor.execute(new CustomRunnable(prites){                @Override                public void doRun() {                    String name = Thread.currentThread().getName();                    System.out.println("curentThread name is "+name +"and prites is "+prites);                    SystemClock.sleep(1000);                }            });        }    }

 public abstract class CustomRunnable implements Runnable,Comparable<CustomRunnable> {        private int priority;        public CustomRunnable(int priority) {            if (priority<0)            throw new IllegalArgumentException();            this.priority = priority;        }        @Override        public int compareTo(CustomRunnable another) {            int my = this.getPriority();            int other = another.getPriority();            if (my>other){                return  -1;            }else{                return 0;            }        }        @Override        public void run() {            doRun();        }        public abstract void doRun();        public int getPriority() {            return priority;        }    }


7、自訂擴充線程池:
public class CustomExpanThreadPool extends ThreadPoolExecutor {    private CustomExpanThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);    }    public static CustomExpanThreadPool getInstance() {        /**         * 擷取CPU數量         */        int processors = Runtime.getRuntime().availableProcessors();        /**         * 核心線程數量         */        int corePoolSize = processors + 1;        /**         * 最大線程數量         */        int maximumPoolSize = processors * 2 + 1;        /**         * 空閑有效時間         */        long keepAliveTime = 60;        /**         * 建立自訂線程池         */        return new CustomExpanThreadPool(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new PriorityBlockingQueue());    }    /**     * 用於控制線程開始與停止執行的方法     */    private boolean isPaused;    private ReentrantLock pauseLock = new ReentrantLock();    private Condition unpaused = pauseLock.newCondition();    /**     * 任務執行前要執行的方法     *     * @param t     * @param r     */    @Override    protected void beforeExecute(Thread t, Runnable r) {        super.beforeExecute(t, r);        System.out.println(Thread.currentThread().getName() + "  任務執行開始 ");        pauseLock.lock();        try {            while (isPaused) unpaused.await();        } catch (InterruptedException ie) {            t.interrupt();        } finally {        }    }    /**     * 任務執行後要執行的方法     *     * @param r     * @param t     */    @Override    protected void afterExecute(Runnable r, Throwable t) {        super.afterExecute(r, t);        System.out.println(Thread.currentThread().getName() + "  任務執行over ");    }    /**     * 線程池關閉後要執行的方法     */    @Override    protected void terminated() {        super.terminated();    }    /**     * 暫停執行任務的方法     */    public void pause() {        pauseLock.lock();        try {            isPaused = true;        } finally {            pauseLock.unlock();        }    }    /**     * 恢複執行任務的方法     */    public void resume() {        pauseLock.lock();        try {            isPaused = false;            unpaused.signalAll();        } finally {            pauseLock.unlock();        }    }}

使用:
 private void customThreadFunction2() {        CustomExpanThreadPool threadPoolExecutor = CustomExpanThreadPool.getInstance();        /**         * 添加執行任務         */        for (int i=1;i<=20;i++){            final int prites = i;            threadPoolExecutor.execute(new CustomRunnable(prites){                @Override                public void doRun() {                    String name = Thread.currentThread().getName();                    System.out.println("curentThread name is "+name +"and prites is "+prites);                    SystemClock.sleep(1000);                }            });        }    }












Android多線程操作——線程池管理綜述

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.