类加载器在加载类时会加锁,当循环加载类时就可能会导致死锁问题,如下示例:
public class TestDeadLock {
static class A {
static {
System.out.println("cinit A");
try {
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e) {
e.printStackTrace();
}
new B();
}
public static void test() {
System.out.println("aaa");
}
}
static class B {
static {
System.out.println("cinit B");
new A();
}
public static void test() {
System.out.println("bbb");
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(() -> A.test()).start();
new Thread(() -> B.test()).start();
}
}