题目 在注释处添加代码 保证输出顺序 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");
}