饿汉式:线程安全
1 直接实例化(简洁直观)
2 枚举(最简洁)
3 静态代码块(适合复杂实例化)
饱汉式
1 线程不安全(适用于单线程)
2 线程安全 ,双端检索dcl+volatile
3 静态内部类形式(适用于多线程)
一、饿汉式
1
public class Singleton1 {
public static final Singleton1 INSTANCE = new Singleton1();
private Singleton1() {};
}
2
public enum Singleton2 {
INSTANCE
}
3
public class Singleton3 {
public static final Singleton3 INSTANCE;
private String info;
static {
Properties pro = new Properties();
try {
pro.load(Singleton3.class.getResourceAsStream("single.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
INSTANCE = new Singleton3(pro.getProperty("info"));
}
private Singleton3(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "Singleton3{" +
"info='" + info + '\'' +
'}';
}
}
二、饱汉式
1
/**
* Created by admin on 2019/3/12 22:17
*
* @Author: created by admin
* @Date: created in 22:17 2019/3/12
* @param: bindingResult
* @param: result
* @return:
* @throws:
* @Description: 线程不安全
* @version:
*/
public class Singleton4 {
private static Singleton4 instance;
private Singleton4() {
}
public static Singleton4 getInstance () throws InterruptedException {
if(instance == null) {
Thread.sleep(100);
instance = new Singleton4();
}
return instance;
}
}
2
/**
* Created by admin on 2019/3/12 22:17
*
* @Author: created by admin
* @Date: created in 22:17 2019/3/12
* @param: bindingResult
* @param: result
* @return:
* @throws:
* @Description: 线程安全的 双端检索dcl+volatile
* @version:
*/
public class Singleton5 {
private static volatile Singleton5 instance;
private Singleton5() {
}
public static Singleton5 getInstance () throws InterruptedException {
if(instance == null) {
synchronized (Singleton5.class) {
if(instance == null) {
Thread.sleep(100);
instance = new Singleton5();
}
}
}
return instance;
}
}
3
/**
* Created by admin on 2019/3/12 22:17
*
* @Author: created by admin
* @Date: created in 22:17 2019/3/12
* @param: bindingResult
* @param: result
* @return:
* @throws:
* @Description: 静态内部类不会自动随着外部类的家中和自动化而初始化,屙屎单独加载和初始化
* 因为是在内部类加载和初始化时候创建的,因此是线程安全的。
* @version: 线程安全,用内部类,饱汉式
*/
public class Singleton6 {
private Singleton6 () {
}
private static class inner {
private static final Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance() {
return inner.INSTANCE;
}
}