饿汉式
类一初始化就加载。
构造方法私有化。
/**
* 饿汉式单例 JVM保证线程安全
*
* 缺点:不管用与否都实例化
*/
public class Mgr01 {
private static final Mgr01 INSTANCE =new Mgr01();
private Mgr01(){};
public static Mgr01 getInstance(){
return INSTANCE;
}
public void m(){
System.out.println("m");
}
public static void main(String[] args) {
Mgr01 m1=Mgr01.getInstance();
Mgr01 m2=Mgr01.getInstance();
System.out.println(m1==m2);
}
}
懒汉式
什么时候用,什么时候加载
懒汉式是线程不安全的需要加synchronized
/**
* 懒汉式
* 什么时候用,什么时候初始化
*/
public class Mgr02 {
private static Mgr02 INSTANCE;
private Mgr02(){};
public static synchronized Mgr02 getInstance(){
if (INSTANCE==null){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
INSTANCE=new Mgr02();
}
return INSTANCE;
}
public void m(){
System.out.println("m");
}
public static void main(String[] args) {
for (int i=0;i<100;i++){
new Thread(()->{
System.out.println(Mgr02.getInstance().hashCode());
}).start();
}
}
}
懒汉式双重检验
public class Singleton {
private static Singleton singleton=null;
private Singleton(){
}
public static Singleton getInstance(){
if (singleton==null){
synchronized (Singleton.class) {
if (singleton==null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
静态内部类
JVM中类只加载一次,保证线程安全
public class Mgr03{
private Mgr03(){};
private static class Mgr03Holder{
private final static Mgr03 INSTANCE=new Mgr03();
}
public static Mgr03 getInstance(){
return Mgr03Holder.INSTANCE;
}
}
枚举
public enum Mgr04 {
INSTANCE;
public static void main(String[] args) {
for (int i=0;i<100;i++){
new Thread(()-> System.out.println(Mgr04.INSTANCE.hashCode())).start();
}
}
}