public class MySingle {
private MySingle() {}
private static MySingle mySingle;
public static MySingle getInstance() {
if (mySingle ==null ) {
mySingle = new MySingle();
}
return mySingle;
}
}
public class MySingle1 {
private MySingle1() {}
private static final MySingle1 mySingle1=new MySingle1();
public static MySingle1 getInstance() {
return mySingle1;
}
}
- 懒汉模式,只有调用对应方法,才会初始化类,导致不是线程安全的。
- 相反饿汉模式,一旦类加载,就会初始化,所以线程安全。