Java併發編程之線程池及示例

一、Executor

  線程池頂級接口。定義方法,void execute(Runnable)。方法是用於處理任務的一個服務方法。調用者提供Runnable 接口的實現,線程池經過線程執行這個 Runnable。服務方法無返回值的。是 Runnable 接口中的 run 方法無返回值。
  經常使用方法 -voidexecute(Runnable) 做用是: 啓動線程任務的。示例以下:java

/**
 * 線程池
 * Executor - 線程池底層處理機制。
 * 在使用線程池的時候,底層如何調用線程中的邏輯。
 */
import java.util.concurrent.Executor;

public class Test_MyExecutor implements Executor {
    public static void main(String[] args) {
        new Test_MyExecutor().execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " - test executor");
            }
        });
    }

    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }
}

二、ExecutorService

  Executor 接口的子接口。提供了一個新的服務方法,submit。有返回值(Future 類型)。 submit 方法提供了 overload 方法。其中有參數類型爲 Runnable 的,不須要提供返回值的; 有參數類型爲 Callable,能夠提供線程執行後的返回值。
  Future,是 submit 方法的返回值。表明將來,也就是線程執行結束後的一種結果。如返 回值。
  常見方法 -void execute(Runnable), Future submit(Callable), Future submit(Runnable) 線程池狀態: Running, ShuttingDown, Terminated。緩存

    Running- 線程池正在執行中。活動狀態。服務器

    ShuttingDown- 線程池正在關閉過程當中。優雅關閉。一旦進入這個狀態,線程池再也不接收新的任務,處理全部已接收的任務,處理完畢後,關閉線程池。 併發

    Terminated- 線程池已經關閉。dom

三、Future

  將來結果,表明線程任務執行結束後的結果。獲取線程執行結果的方式是經過 get 方法獲取的。get 無參,阻塞等待線程執行結束,並獲得結果。get 有參,阻塞固定時長,等待 線程執行結束後的結果,若是在阻塞時長範圍內,線程未執行結束,拋出異常。ide

  經常使用方法: T get()、T get(long, TimeUnit) 。工具

/**
 * 線程池
 * 固定容量線程池
 */
import java.util.concurrent.*;

public class Test_03_Future {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /*FutureTask<String> task = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "first future task";
            }
        });
        
        new Thread(task).start();
        
        System.out.println(task.get());*/

        ExecutorService service = Executors.newFixedThreadPool(1);

        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("aaa");
                return Thread.currentThread().getName() + " - test executor";
            }
        });
        System.out.println(future);
        System.out.println(future.isDone()); // 查看線程是否結束, 任務是否完成。 call方法是否執行結束

        System.out.println(future.get()); // 獲取call方法的返回值。
        System.out.println(future.isDone());
    }
}

四、Callable

  可執行接口。 相似 Runnable 接口。也是能夠啓動一個線程的接口。其中定義的方法是 call。call 方法的做用和 Runnable 中的 run 方法徹底一致。call 方法有返回值。性能

  接口方法 : Object call();至關於 Runnable 接口中的 run 方法。區別爲此方法有返回值。 不能拋出已檢查異常。測試

  Callable、Runnable 接口的選擇:須要返回值或須要拋出異常時,使用 Callable;其餘狀況可任意選擇。this

五、Executors

  工具類型。爲 Executor 線程池提供工具方法。能夠快速的提供若干種線程池。如:固定 容量的,無限容量的,容量爲 1 等各類線程池。

  線程池是一個進程級的重量級資源。默認的生命週期和 JVM 一致。當開啓線程池後, 直到 JVM 關閉爲止,是線程池的默認生命週期。若是手工調用 shutdown 方法,那麼線程池 執行全部的任務後,自動關閉。

  開始 - 建立線程池。
  結束 - JVM 關閉或調用 shutdown 並處理完全部的任務。 相似 Arrays,Collections 等工具類型的功用。

六、FixedThreadPool

  容量固定的線程池。活動狀態和線程池容量是有上限的線程池。全部的線程池中,都有 一個任務隊列。使用的是 BlockingQueue<Runnable>做爲任務的載體。當任務數量大於線程池容量的時候,沒有運行的任務保存在任務隊列中,當線程有空閒的,自動從隊列中取出任務執行。

  使用場景: 大多數狀況下,使用的線程池,首選推薦 FixedThreadPool。OS 系統和硬件是有線程支持上限。不能隨意的無限制提供線程池。

  線程池默認的容量上限是 Integer.MAX_VALUE。 常見的線程池容量: PC:200。 服務器:1000~10000

  線程池容量和併發能力換算關係大約爲:併發量= 10*線程池容量 ~ 18*線程池容量。

  queued tasks- 任務隊列

  completed tasks- 結束任務隊列

/**
 * 線程池
 * 固定容量線程池
 * FixedThreadPool - 固定容量線程池。建立線程池的時候,容量固定。構造的時候,提供線程池最大容量
 * Executors.newFixedThreadPool(int) ->  ExecutorService - 線程池服務類型。全部的線程池類型都實現這個接口。
 * 實現這個接口,表明能夠提供線程池能力。
 * shutdown - 優雅關閉。 不是強行關閉線程池,回收線程池中的資源。而是再也不處理新的任務,將已接收的任務處理完畢後再關閉。
 * Executors - Executor的工具類。相似Collection和Collections的關係,能夠更簡單的建立若干種線程池。
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_02_FixedThreadPool {

    public static void main(String[] args) {
        ExecutorService service =
                Executors.newFixedThreadPool(5);
        for (int i = 0; i < 6; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        service.shutdown();
        // 是否已經結束, 至關於回收了資源。
        System.out.println(service.isTerminated());
        // 是否已經關閉, 是否調用過shutdown方法
        System.out.println(service.isShutdown());
        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);
    }
}

  執行結果:

java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-1 - test executor
pool-1-thread-2 - test executor
pool-1-thread-3 - test executor
pool-1-thread-4 - test executor
pool-1-thread-5 - test executor
pool-1-thread-1 - test executor
true
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]

  注意:FixedThreadPool實現是基於LinkedBlockingQueue的。

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

七、CachedThreadPool

  緩存的線程池容量不限(Integer.MAX_VALUE)。自動擴容。容量管理策略:若是線程 池中的線程數量不知足任務執行,建立新的線程。每次有新任務沒法即時處理的時候,都會 建立新的線程。當線程池中的線程空閒時長達到必定的臨界值(默認 60 秒),自動釋放線程。

  默認線程空閒 60 秒,自動銷燬。
  應用場景: 內部應用或測試應用。 內部應用,有條件的內部數據瞬間處理時應用,如:

  電信平臺夜間執行數據整理:有把握在短期內處理完全部工做,且對硬件和軟件有足夠的信心。 測試應用:在測試的時候,嘗試獲得硬件或軟件的最高負載量,用於提供 FixedThreadPool 容量的指導。

/**
 * 線程池
 * 無容量限制的線程池(最大容量默認爲Integer.MAX_VALUE)
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_05_CachedThreadPool {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        System.out.println(service);

        for (int i = 0; i < 5; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(65);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(service);
    }
}

  運行結果:

java.util.concurrent.ThreadPoolExecutor@483bf400[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
java.util.concurrent.ThreadPoolExecutor@483bf400[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 0]
pool-1-thread-1 - test executor
pool-1-thread-2 - test executor
pool-1-thread-3 - test executor
pool-1-thread-5 - test executor
pool-1-thread-4 - test executor
  注意:CachedThreadPool實現是基於SynchronousQueue的。
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

八、ScheduledThreadPool

  計劃任務線程池。能夠根據計劃自動執行任務的線程池。

scheduleAtFixedRate(Runnable, start_limit, limit, timeunit)

runnable - 要執行的任務。

start_limit - 第一次任務執行的間隔。

limit - 屢次任務執行的間隔。

timeunit - 屢次任務執行間隔的時間單位。

  使用場景: 計劃任務時選用(DelaydQueue),如:電信行業中的數據整理,每分鐘整 理,每小時整理,天天整理等。

/**
 * 線程池
 * 計劃任務線程池。
 */
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test_07_ScheduledThreadPool {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
        System.out.println(service);

        // 定時完成任務。 scheduleAtFixedRate(Runnable, start_limit, limit, timeunit)
        // runnable - 要執行的任務。
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }
        }, 0, 300, TimeUnit.MILLISECONDS);

    }
}

  運行結果:

java.util.concurrent.ScheduledThreadPoolExecutor@483bf400[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
pool-1-thread-1
pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2

  注意:ScheduledThreadPool實現是基於DelayedWorkQueue的。

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
         DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}    

九、SingleThreadExceutor

  單一容量的線程池。
  使用場景: 保證任務順序時使用。如: 遊戲大廳中的公共頻道聊天。秒殺。

/**
 * 線程池
 * 容量爲1的線程池。 順序執行。
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test_06_SingleThreadExecutor {

    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        System.out.println(service);

        for (int i = 0; i < 5; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

    }
}

  運行結果:

java.util.concurrent.Executors$FinalizableDelegatedExecutorService@483bf400
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor

  注意:SingleThreadExceutor實現是基於LinkedBlockingQueue的。

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

十、ForkJoinPool

  分支合併線程池(mapduce 相似的設計思想)。適合用於處理複雜任務。 初始化線程容量與 CPU 核心數相關。
  線程池中運行的內容必須是 ForkJoinTask 的子類型(RecursiveTask,RecursiveAction)。 ForkJoinPool - 分支合併線程池。 能夠遞歸完成複雜任務。要求可分支合併的任務必須是 ForkJoinTask 類型的子類型。其中提供了分支和合並的能力。ForkJoinTask 類型提供了兩個抽象子類型,RecursiveTask 有返回結果的分支合併任務,RecursiveAction無返回結果的分支合併任務。(Callable/Runnable)compute 方法:就是任務的執行邏輯。

  ForkJoinPool 沒有所謂的容量。默認都是 1 個線程。根據任務自動的分支新的子線程。 當子線程任務結束後,自動合併。所謂自動是根據 fork 和 join 兩個方法實現的。

  應用: 主要是作科學計算或天文計算的。數據分析的。

/**
 * 線程池
 * 分支合併線程池。
 */
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class Test_08_ForkJoinPool {

    final static int[] numbers = new int[1000000];
    final static int MAX_SIZE = 50000;
    final static Random r = new Random();


    static {
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = r.nextInt(1000);
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        long result = 0L;
        for (int i = 0; i < numbers.length; i++) {
            result += numbers[i];
        }
        System.out.println(result);

        ForkJoinPool pool = new ForkJoinPool();
        AddTask task = new AddTask(0, numbers.length);

        Future<Long> future = pool.submit(task);
        System.out.println(future.get());

    }

    static class AddTask extends RecursiveTask<Long> { // RecursiveAction
        int begin, end;

        public AddTask(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        //
        protected Long compute() {
            if ((end - begin) < MAX_SIZE) {
                long sum = 0L;
                for (int i = begin; i < end; i++) {
                    sum += numbers[i];
                }
                // System.out.println("form " + begin + " to " + end + " sum is : " + sum);
                return sum;
            } else {
                int middle = begin + (end - begin) / 2;
                AddTask task1 = new AddTask(begin, middle);
                AddTask task2 = new AddTask(middle, end);
                task1.fork();// fork - 就是用於開啓新的任務的。 就是分支工做的。 就是開啓一個新的線程任務。
                task2.fork();
                // join - 合併。將任務的結果獲取。 這是一個阻塞方法。必定會獲得結果數據。
                return task1.join() + task2.join();
            }
        }
    }
}

十一、WorkStealingPool

  JDK1.8 新增的線程池。工做竊取線程池。當線程池中有空閒鏈接時,自動到等待隊列中 竊取未完成任務,自動執行。

  初始化線程容量與 CPU 核心數相關。此線程池中維護的是精靈線程。 ExecutorService.newWorkStealingPool ();

十二、ThreadPoolExecutor

  線程池底層實現。除 ForkJoinPool 外,其餘經常使用線程池底層都是使用 ThreadPoolExecutor實現的。

public ThreadPoolExecutor
  (int corePoolSize, // 核心容量,建立線程池的時候,默認有多少線程。也是線程池保持的最少線程數。
  int maximumPoolSize, // 最大容量,線程池最多有多少線程
  long keepAliveTime, // 生命週期,0爲永久。當線程空閒多久後,自動回收。
  TimeUnit unit, // 生命週期單位,爲生命週期提供單位,如:秒,毫秒
  BlockingQueue<Runnable> workQueue // 任務隊列,阻塞隊列。 注意:泛型必須是 Runnable
);

  使用場景: 默認提供的線程池不知足條件時使用。如:初始線程數據 4,最大線程數 200,線程空閒週期 30 秒。

/**
 * 線程池
 * 模擬固定容量線程池
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test_09_ThreadPoolExecutor {

    public static void main(String[] args) {
        // 模擬fixedThreadPool, 核心線程5個,最大容量5個,線程的生命週期無限。
        ExecutorService service =
                new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < 6; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " - test executor");
                }
            });
        }

        System.out.println(service);

        service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        service.shutdown();
        System.out.println(service.isTerminated());
        System.out.println(service.isShutdown());
        System.out.println(service);

    }
}

  運行結果:

java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-2 - test executor
pool-1-thread-1 - test executor
pool-1-thread-5 - test executor
pool-1-thread-3 - test executor
pool-1-thread-4 - test executor
pool-1-thread-2 - test executor
true
true
java.util.concurrent.ThreadPoolExecutor@71f2a7d5[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]

1三、性能問題

  以下示例爲線程池和單線程運算時的性能測試。

/**
 * 線程池
 * 固定容量線程池, 簡單應用
 */
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Test_04_ParallelComputingWithFixedThreadPool {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        computing(1, 200000);
        long end = System.currentTimeMillis();
        System.out.println("computing times : " + (end - start));

        ExecutorService service = Executors.newFixedThreadPool(5);

        ComputingTask t1 = new ComputingTask(1, 60000);
        ComputingTask t2 = new ComputingTask(60001, 110000);
        ComputingTask t3 = new ComputingTask(110001, 150000);
        ComputingTask t4 = new ComputingTask(150001, 180000);
        ComputingTask t5 = new ComputingTask(180001, 200000);

        Future<List<Integer>> f1 = service.submit(t1);
        Future<List<Integer>> f2 = service.submit(t2);
        Future<List<Integer>> f3 = service.submit(t3);
        Future<List<Integer>> f4 = service.submit(t4);
        Future<List<Integer>> f5 = service.submit(t5);

        start = System.currentTimeMillis();
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        f5.get();
        end = System.currentTimeMillis();
        System.out.println("parallel computing times : " + (end - start));

    }

    private static List<Integer> computing(Integer start, Integer end) {
        List<Integer> results = new ArrayList<>();
        boolean isPrime = true;
        for (int i = start; i <= end; i++) {
            for (int j = 1; j < Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                results.add(i);
            }
            isPrime = true;
        }

        return results;
    }

    static class ComputingTask implements Callable<List<Integer>> {
        int start, end;

        public ComputingTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public List<Integer> call() throws Exception {
            List<Integer> results = new ArrayList<>();
            boolean isPrime = true;
            for (int i = start; i <= end; i++) {
                for (int j = 1; j < Math.sqrt(i); j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime) {
                    results.add(i);
                }
                isPrime = true;
            }

            return results;
        }
    }
}

  運行結果:

computing times : 9
parallel computing times : 1
相關文章
相關標籤/搜索