控制多线程执行顺序的N种方式

130 阅读1分钟

依稀记得刚入行的时候,疯狂的刷面试题,我的写法只是一个线程.join()这种写法,后来随着JDK的升级以及对线程池的掌握、JUC包的掌握,越来越多的方法浮现在眼前,瞬间感觉这样的问题才是最基本的入门问题哈,当然深究到源码中,那就是另外一回事情了

总结一下我的N种写法

  1. 原始的线程.join()方法
public class TestThreadSeq1 {
  public static void main(String[] args) {
      Thread thread1 = new Thread(() -> {

          System.out.println("thread1执行了");
      });
      Thread thread2 = new Thread(() -> {
          try {
              thread1.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread2执行了");
      });
      Thread thread3 = new Thread(() -> {
          try {
              thread2.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread3执行了");
      });

      thread3.start();
      thread2.start();
      thread1.start();
  }
}
  1. 利用只有一个线程的线程池,挨个提交任务排队执行
public class TestThreadSeq1 { 
    
    private static  ExecutorService executorService =  Executors.newFixedThreadPool(1);

  public static void main(String[] args) {
      Thread thread1 = new Thread(() -> {

          System.out.println("thread1执行了");
      });
      Thread thread2 = new Thread(() -> {
          try {
              thread1.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread2执行了");
      });
      Thread thread3 = new Thread(() -> {
          try {
              thread2.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread3执行了");
      });

      executorService.submit(thread3);
      executorService.submit(thread2);
      executorService.submit(thread1);

  }
}
  1. 利用jdk1.8的CompletableFuture
public class TestThreadSeq1 {
  public static void main(String[] args) {
      Thread thread1 = new Thread(() -> {

          System.out.println("thread1执行了");
      });
      Thread thread2 = new Thread(() -> {
          try {
              thread1.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread2执行了");
      });
      Thread thread3 = new Thread(() -> {
          try {
              thread2.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println("thread3执行了");
      });

      CompletableFuture.runAsync(thread3).thenRun(thread2).thenRun(thread1);
  }
}