一、使用join方法实现
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("thread1");
});
Thread thread2= new Thread(() -> {
try {
thread1.join();
System.out.println("thread2");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread3 = new Thread(() -> {
try {
thread1.join();
System.out.println("thread3");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread3.start();
thread2.start();
thread1.start();
}
public static void main(String[] args) {
CountDownLatch countDownLatch1 =new CountDownLatch(1);
CountDownLatch countDownLatch2 =new CountDownLatch(1);
CountDownLatch countDownLatch3=new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
System.out.println("thread1");
countDownLatch1.countDown();
});
Thread thread2 = new Thread(() -> {
try {
countDownLatch1.await();
System.out.println("thread2");
countDownLatch2.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread3 = new Thread(() -> {
try {
countDownLatch2.await();
System.out.println("thread3");
countDownLatch3.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread2.start();
thread3.start();
thread1.start();
}