先来看这个代码是咋写的
public class Lazy {
public static boolean init = false;
static {
Thread t = new Thread(() -> init = true);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(init);
}
}
原问题是最终的输出结果,但实际上什么都不会输出。
我们先给自己创建的线程起个名字,叫"STATIC_JOIN",再通过IDEA看看线程的状态。
我们发现main线程的确阻塞了,然后"STATIC_JOIN"线程一直处在runnable状态,似乎一直在等待着什么。
我们一个个来思考,为什么main线程阻塞了?其实这个不难推测