标签:
首先一个简单的单例类:
public class Logger { private static Logger log = null; // 构造函数私有化 private Logger() { } public static Logger getLogger() { if (log == null) { log = new Logger(); } return log; } }
该类当放入多线程的环境中,肯定 就会出现问题,如何解决?
1,第一种方式:在方法getLogger上加上synchronized关键字:
public static synchronized Logger getLogger(){ if(log == null){ log = new Logger(); } return log; }
public static Logger getLogger(){ synchronized (log) { if(log == null){ log = new Logger(); } } return log; }
public class Logger { private static Logger log = null; //构造函数私有化 private Logger(){} //创建一个私有的静态内部类 private static class LoggerFactory{ private static Logger logger = new Logger(); } public static Logger getLogger(){ return LoggerFactory.logger; } }
方案2:把创建对象和获取对象分开:
public class Logger2 { private static Logger2 log = null; //构造函数私有化 private Logger2(){} public synchronized void setLogger(){ if(log == null){ log = new Logger2(); } } public Logger2 getLogger(){ if(log == null){ setLogger();//初始化log } return log; } }
方案3:采用“影子实例”同步单例对象属性的同步跟新:
public class Logger { private static Logger log = null; private Vector properties = null; public Vector getProperties() { return properties; } public static Logger getLogger(){ if(log == null){ syncInit(); } return log; } public static synchronized void syncInit(){//log对象初始化 if(log == null){ log = new Logger(); } } // 替换掉原有log里面的影子properties public void updatePropertis() { Logger log1 = new Logger(); properties = log1.getProperties(); } // 构造函数私有化 private Logger() { //这里模拟从服务器里面读取配置信息,赋值给properties改对象 } }
标签:
原文地址:http://www.cnblogs.com/my-haohao/p/5613006.html