java 加载类 - 保证 方法线程安全,只被加载过一次
证明 java 加载类保证 方法线程安全,只被加载过一次
public class ClinitTest {
public static void main(String[] args) {
Runnable runnable = () ->{
System.out.println(Thread.currentThread().getName() + "start..");
InitThread initThread = new InitThread();
System.out.println(Thread.currentThread().getName() + "end..");
};
Thread t1 = new Thread(runnable, "thread-1");
Thread t2 = new Thread(runnable, "thread-2");
t1.start();
t2.start();
}
static class InitThread {
static {
if (true){
System.out.println(Thread.currentThread().getName() + " 正在加载..");
while (true){
}
}
}
}
}
结果:
thread-1start..
thread-2start..
thread-2 正在加载..
可以发现 线程2 未加载完 InitThread 类时, thread-1 被阻塞