java自帶線程池Executors

Executors類裏邊常用的四種線程池

public class Executors {

//1.newFixedThreadPool

創建一個定長線程池,可控制線程最大併發數,超出的線程會在無界隊列中等待

public static ExecutorService newFixedThreadPool(int nThreads) {

return new ThreadPoolExecutor(nThreads, nThreads,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue<Runnable>());

}

//2.newSinglethreadExecutor

創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有的任務按照指定的順序(FIFO,LIFO,優先級)執行

public static ExecutorService newSingleThreadExecutor() {

return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue<Runnable>()));

}

//3.newCachedThreadPool

創建一個可緩存線程池,如果線程池超過處理需要,可靈活回收空閒線程,若無回收線程,則新建線程

public static ExecutorService newCachedThreadPool() {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue<Runnable>());

}

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue<Runnable>(),

threadFactory);

}

//4.newScheduledThreadPool

創建一個定長線程池,支持定時及週期性任務執行

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {

        return new ScheduledThreadPoolExecutor(corePoolSize);

    }

}

//四種線程池其實內部方法都是調用的ThreadPoolExecutor類,只不過利用了其不同的構造方法而已(傳入自己需要傳入的參數),那麼利用這個特性,我們自己也是可以實現自己定義的線程池

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章