面试题: 创建3个线程,t1、t2、t3,让让t1在t2之前执行,t2在t3之前执行。
核心: 让其他线程变为等待状态,必须让join方法在其他线程内部调用。
/** * @author: wangqinmin * @date : 2020/7/3 * @description: 仰天大笑出门去,我辈岂是蓬蒿人 */ public class TestJoin { /** * 用一道面试题讲解join * <p> * 创建3个线程,t1 t2 t3 ,让他们按顺序执行。 * <p> * 核心: 让其他线程变为等待状态,必须让join方法在其他线程内部调用。 * <p> * 最后相当于就变成单线程了。正常开发中,很少这样用。 * * @param args */ public static void main(String[] args) { final Thread t1 = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } }); final Thread t2 = new Thread(new Runnable() { public void run() { // 记住: join必须在线程内部使用,才能有效果 try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } }); Thread t3 = new Thread(new Runnable() { public void run() { // 记住: join必须在线程内部使用,才能有效果 try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } }); t1.start(); t2.start(); t3.start(); } }