1. 程式人生 > >Java中Executors類中幾種建立各型別執行緒池的方法及例項

Java中Executors類中幾種建立各型別執行緒池的方法及例項

Executors:提供了一系列靜態工廠方法用於建立各種執行緒池。

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);
    }
例項程式碼下載