Java(Android)線程池 總結

 
 
JAVA的Executors源碼:(能夠看出底層都是經過ThreadPoolExecutor來具體設置的~)
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

  

public static ExecutorService newFixedThreadPool(int nThreads){
        returnnewThreadPoolExecutor(nThreads, nThreads,
                                       0L,TimeUnit.MILLISECONDS,
                                       newLinkedBlockingQueue<Runnable>());
     }

  

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory){
      returnnewFinalizableDelegatedExecutorService
            (newThreadPoolExecutor(1,1,
                                    0L,TimeUnit.MILLISECONDS,
                                    newLinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

  

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){
        returnnewScheduledThreadPoolExecutor(corePoolSize);
    }

  

ScheduledThreadPoolExecutor  : extends ThreadPoolExecutor ,  implements ScheduledExecutorService
 

ThreadPoolExecutor自定義

以上是一些JAVA封裝現成設置後獲得的線程池,更靈活的自定義設置:
ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime,  TimeUnit  unit,  BlockingQueue < Runnable > workQueue,  ThreadFactory  threadFactory,  RejectedExecutionHandler  handler)
 
 
ThreadPoolExecutor提供了一系列參數來配置線程池,經過不一樣的參數能夠建立不一樣的線程池:
1. corePoolSize :核心線程數,默認狀況下,核心線程會在線程中一直存活;
2. maximumPoolSize :最大線程數,當活動線程數達到這個數值後,後續的任務將會被阻塞;
3. keepAliveTime :非核心線程閒置時的超時時長,超過這個時長,閒置的非核心線程就會被回收;
4. unit :用於指定keepAliveTime參數的時間單位,有 TimeUnit.MILLISECONDS TimeUnit.SECONDS TimeUnit.MINUTES 等;
5. workQueue :任務隊列,經過線程池的execute方法提交的Runnable對象會存儲在這個參數中;
6. threadFactory :線程工廠,爲線程池提供建立新線程的功能。它是一個接口,它只有一個方法 Thread newThread(Runnable r)
7. RejectedExecutionHandler :當線程池沒法執行新任務時,多是因爲任務隊列已滿或者是沒法成功執行任務,這個時候就會調用這個 Handler的 rejectedExecution 方法來通知調用者,默認狀況下, rejectedExecution 會直接拋出個 rejectedExecutionException
 
ThreadPoolExecutor執行任務的規則:
1.若是線程池中的線程數未達到核心線程的數量,那麼會直接啓動一個核心線程來執行任務;
2.若是線程池中的線程數量已經達到或者超過核心線程的數量,那麼任務會被插入到任務隊列中排隊等待執行;
3.若是在步驟2中沒法將任務插入到的任務隊列中,多是任務隊列已滿,這個時候若是線程數量沒有達到規定的最大值,那麼會馬上啓動非核心線程來執行這個任務;
4.若是步驟3中線程數量已經達到線程池規定的最大值,那麼就拒絕執行此任務,ThreadPoolExecutor會調用 RejectedExecutionHandler rejectedExecution 方法來通知調用者。
 
使用示例:
自定義線程池工廠類:
public final class ThreadUtils {
    private static final String TAG = ThreadUtils.class.getSimpleName();
 
    //線程池爲無限大,複用線程,靈活回收空閒線程
    // name:線程名字
    public static ThreadPoolExecutor newCachedThreadPool(final String name) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(),
                new CounterThreadFactory(name),
                new LogDiscardPolicy());
    }
 
    //定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待
    //name:線程名字, nThread:線程數
    public static ThreadPoolExecutor newFixedThreadPool(final String name, int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(),
                new CounterThreadFactory(name),
                new LogDiscardPolicy());
    }
 
    //建立一個單線程化的線程池,它只會用惟一的工做線程來執行任務,保證全部任務按照指定順序(FIFO, LIFO, 優先級)執行
    //name:線程名字
    public static ThreadPoolExecutor newSingleThreadExecutor(final String name) {
        return newFixedThreadPool(name, 1);
    }
 
    //建立一個定長線程池,支持定時及週期性任務執行。
    /*使用:
    scheduledThreadPool.schedule(new Runnable() {
        @Override
        public void run() {
            System.out.println("delay 3 seconds");
        }
        }, 3, TimeUnit.SECONDS);  //表示延遲3秒執行。
     */
    public static ScheduledExecutorService newScheduledExecutorService(int nThreads){
        return  Executors.newScheduledThreadPool(nThreads);
    }
 
    public static class LogDiscardPolicy implements RejectedExecutionHandler {
 
        public LogDiscardPolicy() {
        }
 
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            LogUtils.v(TAG, "rejectedExecution() " + r + " is discard.");
        }
    }
 
    public static class CounterThreadFactory implements ThreadFactory {
        private int count;
        private String name;
 
        public CounterThreadFactory(String name) {
            this.name = (name == null ? "Android" : name);
        }
 
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(name + "-thread #" + count++);
            return thread;
        }
    }
}
相關文章
相關標籤/搜索