今天跟大家聊聊JAVA类的初始化
首先我们来数数与类挂钩的元素,包括类变量、静态代码块、类方法;在第一次调用类的地方,会先初始化类变量,再初始化静态代码块。
public class InitRunnable implements Runnable {
private static int cnt = 0;
public void run () {
Init1.getInstance();
synchronized (this) {
System.out.println("第" + ++cnt + "次调用......");
}
}
}
public class Init1 {
private static Init1 instance = new Init1();
static {
System.out.println("静态块只初始化一次....");
}
private Init1() {
System.out.println("Init1 初始化......");
}
public static Init1 getInstance() {
return instance;
}
}
public class TestInit {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable r = new InitRunnable();
new Thread(r).start();
new Thread(r).start();
}
}
另外,Init1类是在Init1.getInstance()第一次调用的时候初始化的,如果类还未初始化完成,进行第二次调用的话,线程会阻塞。并且类变量和静态块都只会初始化一次。