当前位置:编程学习 > JAVA >>

java 实现两种单例模式学习

1、 相对安全
class SingletonTest {
 private static SingletonTest sg = new SingletonTest();//在调用类时,世界加载
 private SingletonTest(){
  //使用private 锁住new SingletonTest()方法
 }
 public static SingletonTest getInstance(){  //使用静态方法生成类
   return sg; www.zzzyk.com
 }
}

2、相对不安全
class SingletonTest {
 private static SingletonTest sg ;
 private SingletonTest(){
  
 }
 public static SingletonTest getInstance(){
   if(sg == null){
    return new SingletonTest();
   }return sg;
 }
}


这种形式如果在多线程环境下,可能会不能单例化。如:当对象为空,两个线程同时进入if(sg == null)语句

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,