添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

延續昨天介紹 Executors 的部份,今天會使用 newFixThreadPool、newSingleThreadExecutor 的方法撰寫 Sample Code,來了解要如何使用這些 Thread Pool。

  • newFixThreadPool 的 Sample code 如下
  • public class ThreadExample implements Runnable {
      @Override
      public void run() {
        String threadName= Thread.currentThread().getName();
        System.out.println("run " + threadName + " thread");
    

    ThreadExample 是執行緒的程式主要會印出目前執行的執行緒名稱為何

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class Test {
      public static void main(String args[]) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        try {
          for (int i = 0; i < 6; i++) {
            fixedThreadPool.execute(new ThreadExample());
        } catch(Exception e){
          throw new RuntimeException(e);
        } finally {
          fixedThreadPool.shutdown();
    

    在主程式會使用 newFixedThreadPool 建立一個執行緒 pool 只能使用固定數量的執行緒,如果使用的執行緒超出了這個數量,就會放在 Queue 裡進行等待其它的執行緒執行完才能執行,執行的結果如下:

    run pool-1-thread-1 thread
    run pool-1-thread-2 thread
    run pool-1-thread-3 thread
    run pool-1-thread-1 thread
    run pool-1-thread-5 thread
    run pool-1-thread-4 thread
    

    從執行的結果可以看出執行緒的編號為 1 到 5,不會超出 5 以外的數字

  • newSingleThreadExecutor 的 sample code 如下
  • import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class Test {
      public static void main(String args[]) {
        ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
        try {
          for (int i = 0; i < 6; i++) {
            singleThreadPool.execute(new ThreadExample());
        } catch(Exception e){
          throw new RuntimeException(e);
        } finally {
          singleThreadPool.shutdown();
    

    以上的程式使用了 newSingleThreadExecutor 建立了單執行緒的 thread pool,所以程式只會有一個執行緒在執行,執行結果如下:

    run pool-1-thread-1 thread
    run pool-1-thread-1 thread
    run pool-1-thread-1 thread
    run pool-1-thread-1 thread
    run pool-1-thread-1 thread
    run pool-1-thread-1 thread
    

    從以上的執行結果可以看出只會有 pool-1-thread-1 的執行緒在執行,因此證明了只有一個執行緒執行。

    關於 newScheduledThreadPool 和 newSingleThreadScheduledExecutor 可以進行定期的排程執行緒 Pool 的執行,留到明天繼續的介紹。