A:饿汉式
* class Single{
* private float height;
* private Single(){};
* private static Single s=new Single();//先初始化对象
* public static Single getInstance(){
* return s;
* }
* }
*
* B:懒汉式(存在线程安全问题)
* class Single{
* private float height;
* private Single(){};
* private static Single s=null;
* private static Single getInstance(){
* if(s==null){//双重if判断,在确保线程安全的前提下,提高代码的执行效率
* synchronized(Single.class)//线程安全问题解决方法(上锁)
* if(s==null){
* s=new Single();
* }
* }
* return s;
* }
* }
|
|