首页 > 解决方案 > java线程顺序

问题描述

 public static void main(String[] args) throws InterruptedException {
     Thread thread1 = new Thread(() -> System.out.println("thread1"));
     Thread thread2 = new Thread(() -> System.out.println("thread2"));
     Thread thread3 = new Thread(() -> System.out.println("thread3"));
     Thread thread4 = new Thread(() -> System.out.println("thread4"));
     Thread thread5 = new Thread(() -> System.out.println("thread5"));

     thread5.start();
     thread3.start();
     thread1.start();
     thread3.join();
     thread2.start();
     thread1.join();
     thread4.start();
     thread2.join();
     thread4.join();
     thread5.join();
  }

我认为这次运行的结果将是随机的。但是,5、3 和 1 始终排在第一位。

结果1

thread3
thread1
thread5
thread2
thread4

结果2

thread3
thread1
thread5
thread2
thread4

结果3

thread5
thread1
thread3
thread2
thread4

始终执行 5,1,3,然后执行 2,4。为什么会有订单?

标签: javamultithreading

解决方案


推荐阅读