//饿汉式,在多线程下是安全的 public class Single { private static final Single s=new Single(); private Single(){}; public static Single getInstance(){ return s; } }
//懒汉式,非线程安全,必须使用同步 public class Single { private static Single s=null; private Single(){}; public static Single getInstance(){ if(s==null) synchronized(Single.class){//静态同步,锁是方法所在类的字节码文件对象 if(s==null) s=new Single(); } return s; } }
时间: 2024-12-15 01:38:10