设计模式之懒汉单例线程安全

来源:互联网 发布:网络信息管理办法 编辑:程序博客网 时间:2024/05/18 02:03
package design.singletonLazy.demo;public class Main2 {    public static void main(String[] args) {        // 创建多线程验证        Thread t1 = new Thread() {            @Override            public void run() {                SingletonLazySafetyEntity s = SingletonLazySafetyEntity.getSingletonEntity();                System.out.println("t1线程获取对象的hashcode: " + s.hashCode());            }        };        Thread t2 = new Thread() {            @Override            public void run() {                SingletonLazySafetyEntity s = SingletonLazySafetyEntity.getSingletonEntity();                System.out.println("t2线程获取对象的hashcode: " + s.hashCode());            }        };        Thread t3 = new Thread() {            @Override            public void run() {                SingletonLazySafetyEntity s = SingletonLazySafetyEntity.getSingletonEntity();                System.out.println("t3线程获取对象的hashcode: " + s.hashCode());            }        };        t1.start();        t2.start();        t3.start();    }}// t2线程获取对象的hashcode: 798732982// t1线程获取对象的hashcode: 798732982// t3线程获取对象的hashcode: 798732982
package design.singletonLazy.demo;//懒汉式单例-线程安全(序列化和反序列化可能会破坏单例)public class SingletonLazySafetyEntity {    private static class SingletonLazyInnerEntity {        // 创建内部类时直接创建对象实例        private static SingletonLazySafetyEntity s = new SingletonLazySafetyEntity();    }    // 实例输出出口    public static SingletonLazySafetyEntity getSingletonEntity() {        return SingletonLazyInnerEntity.s;    }    // 私有化构造方法,让外部无法通过new创建    private SingletonLazySafetyEntity() {    }}
原创粉丝点击