单例设计模式
饿汉式单例模式
不论是否使用,在类加载的时候实例化完成.
public class Singleton {
private TestSingleton(){
System.out.println("饿汉式单例");
}
private static Singleton INSTANCE = new Singleton();
public static Singleton getInstance(){
return INSTANCE;
}
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
}
}
懒汉式单例模式
在需要使用的时候再进行加载, 但是多线程环境下会存在线程不安全问题
public class Singleton {
private Singleton(){
System.out.println("懒汉式单例");
}
public static TestSingleton getInstance(){
return new TestSingleton();
}
public static void main(String[] args) {
TestSingleton singleton = TestSingleton.getInstance();
System.out.println(singleton);
}
}
线程安全的懒汉式单例模式
DCL---Double Check Lock
双重检验
public class Singleton {
private static volatile Singleton INSTANCE; //禁止指令重排序
private Singleton(){
System.out.println("懒汉式单例");
}
public static Singleton getInstance(){
//双重校验
if (INSTANCE == null){
synchronized (Singleton.class){
if (INSTANCE == null){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
}
}
不加锁的线程安全的单例模式
public class Singleton {
private Singleton() {
System.out.println("single");
}
private static class Inner{
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance() {
return Inner.singleton;
}
public static void main(String[] args) {
Thread[] threads = new Thread[200];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(()->{
System.out.println(Singleton.getInstance());
});
}
Arrays.asList(threads).forEach(o->o.start());
}
}
枚举类型单例模式
public enum Singleton4 {
INSTANCE;
public void m() {}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton4.INSTANCE.hashCode());
}).start();
}
}
}