Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍两种:懒汉式单例、饿汉式单例,并分析其并发问题
单例模式有以下特点:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。
懒汉式
package my.prc.singleton;
/**
*
* @author Administrator
* 懒汉式单例
*/
public class Singleton_LH {
//私有化构造方法,在请求的时候才去实例化对象
private Singleton_LH(){
}
private static Singleton_LH singleton;
public static Singleton_LH getInstance(){
if(singleton==null){
singleton =new Singleton_LH();
}
return singleton;
}
}
//饿汉式
package my.prc.singleton;
public class Singleton_EH {
private Singleton_EH(){}
private static final Singleton_EH singleton =new Singleton_EH();
public static Singleton_EH getInstance(){
return singleton;
}
}
//测试类
package my.prc.singleton;
public class Test implements Runnable{
public static void main(String[] args) {
Test t1 =new Test();
Test t2 =new Test();
Thread thread1 =new Thread(t1);
Thread thread2 =new Thread(t2);
thread1.start();
thread2.start();
}
@Override
public void run() {
System.out.println(Singleton_LH.getInstance()+"懒汉");
System.out.println(Singleton_EH.getInstance()+"饿汉");
}
}
//输出结果
my.prc.singleton.Singleton_LH@1f031d8懒汉
my.prc.singleton.Singleton_LH@1f9ddd8懒汉
my.prc.singleton.Singleton_EH@13e2717饿汉
my.prc.singleton.Singleton_EH@13e2717饿汉
可以看出懒汉式的是线程不安全的,饿汉式的是线程安全的
解决懒汉式并发问题
在方法上加关键字synchronized
package my.prc.singleton;
/**
*
* @author Administrator
* 懒汉式单例
*/
public class Singleton_LH {
//私有化构造方法,在请求的时候才去实例化对象
private Singleton_LH(){
}
private static Singleton_LH singleton;
public static synchronized Singleton_LH getInstance(){
if(singleton==null){
singleton =new Singleton_LH();
}
return singleton;
}
}
测试结果
my.prc.singleton.Singleton_LH@1b250a4懒汉
my.prc.singleton.Singleton_LH@1b250a4懒汉
my.prc.singleton.Singleton_EH@175ae22饿汉
my.prc.singleton.Singleton_EH@175ae22饿汉
但是,synchronized关键字锁住的是这个对象,这样的用法,在性能上会有所下降,因为每次调用getInstance(),都要对对象上锁,事实上,只有在第一次创建对象的时候需要加锁,之后就不需要了,所以,这个地方需要改进。