首页 > 学院 > 开发设计 > 正文

JAVA多线程下创建单例的正确方式

2019-11-14 12:09:22
字体:
来源:转载
供稿:网友

一、不注重性能的情况

package singleton;public class SlowSingleton {    PRivate static SlowSingleton instance;    private SlowSingleton() {    };    public static synchronized SlowSingleton getInstance() {        if (instance == null) {            instance = new SlowSingleton();        }        return instance;    }}二、注重性能,急切创建实例的方案

package singleton;public class FastSingleton {    private static FastSingleton instance = new FastSingleton();    private FastSingleton() {    };    public static FastSingleton getInstance() {        return instance;    }}

这种方法的缺点是:不能延迟实例化

三、注重性能,double check 方案

package singleton;public class DoubleCheckSingleton {    private volatile static DoubleCheckSingleton instance;    private DoubleCheckSingleton() {    };    public static DoubleCheckSingleton getInstance() {        if (instance == null) {            synchronized (DoubleCheckSingleton.class) {                if (instance == null) {                    instance = new DoubleCheckSingleton();                }            }        }        return instance;    }}四、注重性能,静态内部类方案
package singleton;public class MagicSingleton {    private static class SingletonHolder {        private static final MagicSingleton INSTANCE = new MagicSingleton();    }    private MagicSingleton() {    }    public static final MagicSingleton getInstance() {        return SingletonHolder.INSTANCE;    }}

五、注重性能,枚举类方案

package singleton;public enum EnumSingleton {    INSTACE;         public static EnumSingleton getInstance() {        return INSTACE;    }         public void someMethod(){        System.out.println("ooo");    }         // 使用方法    public static void main(String[] args) {        EnumSingleton.INSTACE.someMethod();        // 或者        EnumSingleton.getInstance().someMethod();    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表