困惑(线程锁)

来源:转载

写两种常用的单例模式实现,对比一下两种方式的实现有什么差异:

No1:

[java] 

public class Test { 

     

    private static Test instance = null; 

     

    public static Test getInstance() 

    { 

        synchronized (Test.class) {                 if (instance == null) { 
                    instance = new Test(); 
            } 
        } 
        return instance; 
    } 

public class Test {
 
 private static Test instance = null;
 
 public static Test getInstance()
 {
  synchronized (Test.class) {
          if (instance == null) {
           instance = new Test();
      }
  }
  return instance;
 }
}

No2:


[java] 
public class Test { 
     
    private static Test instance = null; 
     
    public synchronized static Test getInstance() 
    { 
        if (instance == null) { 
            instance = new Test(); 
        } 
        return instance; 
    } 

public class Test {
 
 private static Test instance = null;
 
 public synchronized static Test getInstance()
 {
  if (instance == null) {
   instance = new Test();
  }
  return instance;
 }
}


 


分享给朋友:
您可能感兴趣的文章:
随机阅读: