_128_Java_互斥锁以及懒汉式单例模式线程安全问题的解决

 

//懒汉式单例模式的线程安全问题
//对于一般的方法而言,使用同步代码块,可以考虑使用this
//对于静态方法而言,使用当前类本身来充当。
public class _001_TestMutexLock {
	//InnerClass
	private static class Singleton{
		
		private Singleton() {
			
		}
		private static Singleton instance=null;
		
		public static Singleton getInstance() {
			if(instance==null) {
				synchronized (Singleton.class) {
					if(instance==null) {
						instance=new Singleton();
					}
				}
			}
			return instance;
		}
		
	}
	
	public static void main(String[] args) {
		_001_TestMutexLock.Singleton a = new _001_TestMutexLock.Singleton();
		_001_TestMutexLock.Singleton b = new _001_TestMutexLock.Singleton();
		Singleton instance = a.getInstance();
		Singleton instance2 = b.getInstance();
		System.out.println(instance==instance2);
	}
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-25
  • 2021-06-26
  • 2021-06-09
  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-10
  • 2021-11-13
  • 2022-12-23
相关资源
相似解决方案