Java中四种线程安全的单例模式实现⽅式
第⼀种:饿汉模式(线程安全)
public class Single2 {
private static Single2 instance = new Single2();
private Single2(){
System.out.println("Single2: " + System.nanoTime());
}
public static Single2 getInstance(){
return instance;
}
}
第⼆种:懒汉模式(如果⽅法没有synchronized,则线程不安全)
public class Single3 {
private static Single3 instance = null;
private Single3(){
System.out.println("Single3: " + System.nanoTime());
}
public static synchronized Single3 getInstance(){
if(instance == null){
instance = new Single3();
}
return instance;
}
}
第三种:懒汉模式改良版(线程安全,使⽤了double-check,即check-加锁-check,⽬的是为了减少同步的开销)
public class Single4 {
private volatile static Single4 instance = null;
private Single4(){
System.out.println("Single4: " + System.nanoTime());
}
public static Single4 getInstance(){
if(instance == null){
synchronized (Single4.class) {
单例模式的几种实现方式if(instance == null){
instance = new Single4();
}
}
}
return instance;
}
}
第四种:利⽤私有的内部⼯⼚类(线程安全,内部类也可以换成内部接⼝,不过⼯⼚类变量的作⽤域要改为public了。)
public class Singleton {
private Singleton(){
System.out.println("Singleton: " + System.nanoTime());
}
public static Singleton getInstance(){
return SingletonFactory.singletonInstance;
}
private static class SingletonFactory{
private static Singleton singletonInstance = new Singleton();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。