面试题 添加代码保证线程顺序

题目 在注释处添加代码 保证输出顺序 1 2 3 4

// 0
public static void main(String[] args) {
    new Thread(() -> {
        // 2
        
        System.out.println("2");
    }).start();
    // 1
    
    System.out.println("1");
    new Thread(() -> {
        // 3

        System.out.println("3");
    }).start();
    // 4
    
    System.out.println("4");
}

由于不能再线程尾部添加代码, 所以不能使用锁,不能使用CountdownLatch, 所以可以考虑使用变量保存线程, 使用join逐个阻塞, 但是要保证主线程执行到1之后
还需要考虑指令重排序问题

方案一

// 0
public static volatile Thread t1 = null, t2 = null;
public static CountDownLatch c = new CountDownLatch(1);
public static void main(String[] args) {
    new Thread(() -> {
        // 2
        try {
            c.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1 = Thread.currentThread();
        System.out.println("2");
    }).start();
    // 1
    System.out.println("1");
    new Thread(() -> {
        // 3
        while (true) {
            if (t1 != null) {
                break;
            }
        }
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2 = Thread.currentThread();

        System.out.println("3");
    }).start();
    // 4
    c.countDown();
    while (true) {
        if (t2 != null) {
            break;
        }
    }
    try {
        t2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("4");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值