java 实现两种单例模式学习

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  1、 相对安全

  class SingletonTest {

  private static SingletonTest sg = new SingletonTest();//在调用类时,世界加载

  private SingletonTest(){

  //使用private 锁住new SingletonTest()方法

  }

  public static SingletonTest getInstance(){ //使用静态方法生成类

  return sg; www.2cto.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 实现两种单例模式学习

相关文章:

你感兴趣的文章:

标签云: