加同步锁的单例模式代码
来源:优易学  2011-12-13 13:32:15   【优易学:中国教育考试门户网】   资料下载   IT书店
  /*
  *单例模式
  *单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点。
  *加同步锁的单例模式,适合在多线程中使用。
  */
  class Singleton{
  private static Singleton instance;
  private Singleton(){}//构造函数为private,外类不能使用new来创建立此类的实例
  public static Singleton getInstance(){//获得实例的唯一全局访问点
  System.out.println("进入外层");
  if (instance==null){
  synchronized(Singleton.class){
  if(instance==null){
  instance=new Singleton();
  System.out.println("进入里层");
  }//end inner if
  }//end synchronized
  }//end outter if
  return instance;
  }//end getInstance()
  }
  class Instance extends Thread{
  static int count=1;
  public void run(){
  System.out.println("第"+ count++ +"次调用同一个实例!");
  Singleton s1=Singleton.getInstance();
  }//end run
  public static void main(String []args){
  for( int i=1;i<5;i++){
  Instance thread1=new Instance();
  thread1.start();
  }
  }//end main
  }
  运行结果:
  第1次调用同一个实例!
  进入外层
  进入里层
  第2次调用同一个实例!
  进入外层
  第3次调用同一个实例!
  进入外层
  第4次调用同一个实例!
  进入外层

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训