在项目中有时候就需要用到单例模式,通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.比如你的log,每个功能都会写log,但是我们只需要一个实例来进行.
懒汉模式:
public class First {
private static First instance;
private First(){}
public static First getInstance(){
if (instance == null) {
instance = new SingletonDemo1();
}
return instance;
}
}
但是很明显,不能用于多线程的工作.多个线程同时进行判断的时候还是会出问题.
懒汉模式(加锁)
public class Second {
private static Second instance;
private Second(){}
public static synchronized Second getInstance(){
if (instance == null) {
instance = new Second();
}
return instance;
}
}
这种方法可以解决多线程同时进行访问的问题,但是由于加了锁,进入到方法的时候会等待上一个线程把资源释放出来.那么效率就非常低了.
饿汉模式
public class Third {
private static Third instance = new Third();
private Third(){}
public static Third getInstance(){
return instance;
}
}
这种方法会在类实例化的时候就加载,如果不用的话会造成资源的浪费.
双重锁模式
public class Fourth {
private volatile static Fourth fourth;
private Fourth(){}
public static Fourth getInstance(){
if (Fourth == null) {
synchronized (Fourth.class) {
if (fourth == null) {
fourth = new Fourth();
}
}
}
return fourth;
}
}
这种双重锁模式可以有效的防止资源浪费和解决多线程的问题,其中第二个锁就是为了防止多线程执行过第一个锁之后第一个线程继续执行,而第二个进行等待,等第一个线程执行过其实已经创建过实例了但是第二个线程进行执行的时候需要再进行一次判断.
网友评论