单例模式是设计模式中比较常用的,今天我要详细的了解一下,并且进行一些比较
public class Singleton {
//线程不安全,当多线程的时候可能有多个线程进入if(instance == null)的判断中
private static Singleton instance = null;
//私有化构造函数,这就保证了对象不能被new出来
private Singleton (){
}
public static Singleton getInstance(){
if(instance == null){
//为了测试效果明显,让线程有时间进来
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//单例模式的精髓就在这,类的内部可以new
instance = new Singleton();
}
return instance;
}
//对这种写法的多线程的不安全的测试
public static void main(String[] args) {
Thread thread1 = new Thread(){
public void run() {
System.out.println(getInstance().hashCode());
};
};
Thread thread2 =new Thread(){
public void run() {
System.out.println(getInstance().hashCode());
};
};
thread1.start();
thread2.start();
}
}
按照单例模式,每个类只有一个对象,就是hashcode应该是一样的。结果却是不一致,这样的单例模式在多线程下是不对的。
21281040
12271841
解决真个问题最直接的方法就是同步(synchronized)
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
public static Singleton getInstance(){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
return instance;
}
这两种方法其实差不多,都是在调用getInstance()进行同步,加锁。可以解决多线程下的安全性,但是每次调用getInstance()方法就会加锁解锁,是不是效率太低呢,下面通过两层判断来提高效率
public static Singleton getInstance(){
//第一层判断就可以排除绝大多数调用
if(instance == null){
//在多线程的情况下,一开始可能有多个instance = null的情况进来
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
上面的模式俗称懒汉式,调用getInstance()才会创建对象。
下面的是饿汉式,在类创建的同时就已经创建好一个静态的对象。
//饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
通过静态内部类的方式,实现线程安全。
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
//静态内部类只会被加载一次
static class InstanceHolder{
private static Singleton instance = new Singleton();
}
}
这几种基本就是单例常用的方式