java单例模式在开发中经常使用,小编今天总结了下已知几种方法。
方法一:只适合单线程。(不建议使用)
package com.mec.about_singleton;
public class AboutSingleton {
private static AboutSingleton me = null; //me是自己
private AboutSingleton() {
}
public static AboutSingleton newInstance() {
//如果自己被实例化过就返回自己,如果没有就new一个自己。
if(me == null) {
me = new AboutSingleton();
}
return me;
}
}
方法二:适合多线程(懒汉式)。
package com.mec.about_singleton;
public class AboutSingleton {
//这里强烈建议加volatile,因为是多线程环境,要内存器拒绝优化。
private volatile static AboutSingleton me = null;
private AboutSingleton() {
}
public static AboutSingleton newInstance() {
//如果自己被实例化过就返回自己,如果没有就new一个自己。
if(me == null) {
//因为是多线程所以要加锁,锁可以加到方法上,也可以加到这里。
//但是锁加到方法上,会影响程序运行效率。因为该类是多线程,可能同时调用很多newInstance();
//这里加到if里面会很大提升效率。
synchronized (AboutSingleton.class) {
//这里必须要再次判断因为在多线程环境下,有可能多个线程都运行到了if里面。
//也就是me=null成立。此时一个线程把me值改了,其他的线程就不应该再次实例化。
if(me == null) {
me = new AboutSingleton();
}
}
}
return me;
}
}
方法三,适合多线程使用,采用静态块(饿汉式),建议使用。
package com.mec.about_singleton;
public class AboutSingleton {
//采用静态块初始化,保证单例。但是由于是静态块,所以在类装载时候就实例化了。
private static final AboutSingleton me;
static {
me = new AboutSingleton();
}
private AboutSingleton() {
}
public static AboutSingleton newInstance() {
//直接返回me就行;
return me;
}
}
方法四,适合多线程,采用静态内部类
package com.mec.about_singleton;
public class AboutSingleton {
private AboutSingleton() {
}
//因为该类是static修饰所以会里面实例化一个AboutSingleton类。
private static class Creatclass{
private final static AboutSingleton me = new AboutSingleton();
}
public static AboutSingleton newInstance() {
return Creatclass.me;
}
}