03_ 单例设计模式_双重检查锁定

来源:互联网 发布:联通云数据与联通关系 编辑:程序博客网 时间:2024/05/18 00:44
package com.thread.demo02;/*单例设计模式。*///饿汉式。/*class Single{private static final Single s = new Single();private Single(){}public static Single getInstance(){return s;}}*///懒汉式,实例的延迟加载,//有,多线程访问,存在同步问题//加同步方法//双重检查锁定//使用的锁该方法所在类的字节码文件class Single{private static Single s = null;private Single(){}/**静态的同步方法*/public static  Single getInstance(){/**双重检查锁定:稍微性提高了效率*/if(s==null){synchronized(Single.class)//使用的锁是该方法所在类的字节码文件对象,类名.class,是唯一的{if(s==null)//--->A;s = new Single();}}return s;}}class SingleDemo {public static void main(String[] args) {System.out.println("Hello World!");}}

0 0
原创粉丝点击