/*
*懒汉模式 也是常用的模式
*/
public class Singleton {
//1:让外部不能通过构造方法来实例化这个类
private Singleton(){
}
//2:创建一个private static 的Singleton变量
private static Singleton instance=null;
//3:创建一个public static 的获取唯一实例的方法
public static synchronized Singleton getInstance(){
if(instance==null){
//可以在内部使用无参构造方法
instance=new Singleton();
}
return instance;
}
}
/*
* 第二种形式 饿汉模式
*/
class Singleton2{
private Singleton2(){
}
private static Singleton2 instance=new Singleton2();
public static Singleton2 getInstance(){
return instance;
}
}
public class test {
public static void main(String []args){
Singleton instance=Singleton.getInstance();
Singleton instance2=Singleton.getInstance();
Singleton2 instance3=Singleton2.getInstance();
Singleton2 instance4=Singleton2.getInstance();
Singleton3 instance5=Singleton3.getInstance();
Singleton3 instance6=Singleton3.getInstance();
if(instance3==instance4){
System.out.println("这两个是同一个实例");
}else{
System.out.println("不是同一个实例");
}
if(instance5==instance6){
System.out.println("这两个是同一个实例");
}else{
System.out.println("不是同一个实例");
}
if(instance==instance2){
System.out.println("这两个是同一个实例");
}else{
System.out.println("不是同一个实例");
}
}
}
/*
* 第三种模式:双重锁模式
* 这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。
*这种模式中双重判断加同步的方式,比第一个例子中的效率大大提升,因为如果单层if判断,在服务器允许的情况下,
*假设有一百个线程,耗费的时间为100*(同步判断时间+if判断时间),而如果双重if判断,100的线程可以同时if判断,理论消耗的时间只有一个if判断的时间。
*所以如果面对高并发的情况,而且采用的是懒汉模式,最好的选择就是双重判断加同步的方式。
*/
class Singleton3{
private static volatile Singleton3 instance=null;
private Singleton3(){
}
public static Singleton3 getInstance(){
if(instance==null){
synchronized (Singleton3.class) {
if(instance==null){
instance=new Singleton3();
}
}
}
return instance;
}
}
总结:
饿汉模式,类加载时就创建唯一实例,后面直接获取,线程安全;
懒汉模式,类加载时不用创建,第一个对象获取时创建实例,线程不安全;多线程如果不加锁,可能会创建出多个实例。