天天看點

Java中 ExecutorService四種線程池簡單說明

package com.leitan.architect.threads.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lei.tan
 * @Date: 2018-11-14 15:05
 */
public class ThreadPoolTest {

    /**
     * CachedThreadPool
     * 建立一個可緩存線程池,如果線程池數量超過處理需要,可自動回收空閑線程,如果無可回收線程則建立線程
     */
    public static void cachedThreadPoolTest() {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(index * 200);// 如果不延遲可能出現多個線程
            } catch (Exception e) {
                e.printStackTrace();
            }

            cachedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + ": " + index));
            if (i == 9) cachedThreadPool.shutdown();
        }
    }

    /**
     * FixedThreadPool
     * 建立一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待
     */
    public static void fixedThreadPoolTest() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            fixedThreadPool.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + ": " + index);
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            if (i == 9) fixedThreadPool.shutdown();
        }
    }

    /**
     * ScheduledThreadPool
     * 建立一個定長線程池,支援定時及周期性任務執行。延遲執行示例代碼如下:
     */
    public static void scheduleThreadPoolTest1() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(() -> System.out.println(Thread.currentThread().getName() + ": 延遲了3秒,我開始做事...."), 3, TimeUnit.SECONDS);
        for (int i = 1; i <= 3; i++) {
            try {
                Thread.sleep(1000 - 10);
                System.out.println("第" + i + "秒...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ScheduledThreadPool
     * 建立一個定長線程池,支援定時及周期性任務執行。周期執行示例代碼如下:
     */
    public static void scheduleThreadPoolTest2() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        // 表示延遲1秒後每3秒執行一次。 ScheduledExecutorService比Timer更安全,功能更強大
        scheduledThreadPool.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName() + ": delay 1 seconds, and excute every 3 seconds"), 1, 3, TimeUnit.SECONDS);
    }

    /**
     * SingleThreadExecutor
     * 建立一個單線程化的線程池,它隻會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行
     */
    public static void singleThreadExecutorTest() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + ": " + index);
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }


    public static void main(String[] args) {
        // CachedThreadPool
        // 建立一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程
//        cachedThreadPoolTest();

        // FixedThreadPool
        // 建立一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待
        fixedThreadPoolTest();


        // ScheduledThreadPool
        // 建立一個定長線程池,支援定時及周期性任務執行。延遲執行示例代碼如下:
//        scheduleThreadPoolTest1();

        // ScheduledThreadPool
        // 建立一個定長線程池,支援定時及周期性任務執行。周期執行示例代碼如下:
//        scheduleThreadPoolTest2();

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

    }

}



           

繼續閱讀