Java中Executors類中幾種建立各類型線程池的方法及執行個體__線程池

來源:互聯網
上載者:User

Executors:提供了一系列靜態Factory 方法用於建立各種線程池。 1.Executors.newCachedThreadPool建立可變線程池

如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。核心線程池大小為0,最大為Integer.MAX_VALUE,線程空閑存活時間是60秒。 範例程式碼:

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();        for (int i = 1; i <= 5; i++) {            final int index = i;            cachedThreadPool.execute(() -> {                System.out.println(index + "start");                System.out.println(Thread.currentThread().getName());                try {                    Thread.sleep(index * 1500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println(index + "end");        });}

執行結果:

Executors內部建立newCachedThreadPool源碼

public static ExecutorService newCachedThreadPool() {        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue<Runnable>());}

2.Executors.newFixedThreadPool建立固定大小線程池 核心線程數即為最大線程數,線程不會被回收,直到調用shutdown方法回收 執行個體代碼:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);for (int i = 1; i <= 4; i++) {            final int index = i;            System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());            fixedThreadPool.execute(() -> {                try {                    System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());                    Thread.sleep(1500);                    System.out.println(Thread.currentThread().getName() + "end");                } catch (InterruptedException e) {                    e.printStackTrace();                }        }); }
執行結果:
可以看到一直都是兩個線程執行。 Executors內部建立newFixedThreadPool源碼
public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>());}

3.Executors.newScheduledThreadPool建立定時或週期性任務執行線程池 該線程池可用於定時或週期性任務的執行 定時執行個體代碼:
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);    System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());    //建立線程池後3秒執行    scheduledThreadPool.schedule(() -> {        System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());        System.out.println("delay 3 seconds");}, 3, TimeUnit.SECONDS);
定時執行結果:
周期執行個體代碼:
ScheduledExecutorService scheduleThreadPoolAtFixedRate = Executors.newScheduledThreadPool(5);System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());//建立線程池後1秒執行 , 之後每3秒執行一次scheduleThreadPoolAtFixedRate.scheduleAtFixedRate(() -> {      System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());      System.out.println("delay 1 seconds, and excute every 3 seconds");}, 1, 3, TimeUnit.SECONDS);
周期執行結果:
Executors內部建立newScheduledThreadPool源碼
 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {        return new ScheduledThreadPoolExecutor(corePoolSize); }public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,              new DelayedWorkQueue()); }
4.Executors.singleThreadExecutor建立單線的線程池 該線程池有且僅有一個線程執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。 執行個體代碼:
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();for (int i = 1; i <= 4; i++) {            final int index = i;            System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());            singleThreadExecutor.execute(() -> {                try {                    System.out.println(Thread.currentThread().getName() + "時間" + System.currentTimeMillis());                    Thread.sleep(1500);                    System.out.println(Thread.currentThread().getName() + "end");                } catch (InterruptedException e) {                    e.printStackTrace();                }        });}
運行結果:
Executors內部建立newSingleThreadExecutor源碼
public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(1, 1,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue<Runnable>()));}
4.Executors.newWorkStealingPool建立並存執行線程池 建立一個擁有多個任務隊列(以便減少串連數)的線程池 執行個體代碼:
// 設定並行層級為2,即預設每時每刻只有2個線程同時執行        ExecutorService newWorkStealingPool = Executors.newWorkStealingPool(2);        for (int i = 1; i <= 4; i++) {            final int count = i;            System.out.println("execute" + i);            newWorkStealingPool.execute(() -> {                try {                    Thread.sleep(1000);//此任務耗時1s                    System.out.println("線程" + Thread.currentThread().getName() + "完成任務:"                            + count + "   時間為:" + System.currentTimeMillis());                } catch (InterruptedException e) {                    e.printStackTrace();                }            });        }
運行結果:
Executors內部建立newWorkStealingPool源碼
public static ExecutorService newWorkStealingPool(int parallelism) {        return new ForkJoinPool            (parallelism,             ForkJoinPool.defaultForkJoinWorkerThreadFactory,             null, true);    }

執行個體代碼下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.