Singleton_单例模式:
常规实现:
public class Singleton{
private Singleton(){
}
private final static Singleton INSTANCE=new Singleton();
public static Singleton getInstance(){
return INSTANCE;
}
public static void main(String[] args){
for(int=0;i<100:i++){
new Thread(()->{
System.out.println(Singleton.getInstance().hashCode());
}).start();
}
}
}
内部类实现:
public class Singleton{
private Singleton(){
}
private static class SingletonHlder{
private final static Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return SingletonHlder.INSTANCE;
}
public static void main(String[] args){
for(int=0;i<100:i++){
new Thread(()->{
System.out.println(Singleton.getInstance().hashCode());
}).start();
}
}
}
枚举类型实现:
public enum Singleton{
INSTANCE;
public static void main(String[] args){
for(int=0;i<100:i++){
new Thread(()->{
System.out.println(Singleton.INSTANCE.hashCode());
}).start();
}
}
}