一、整体代码

        Singleton.java

 

public class Singleton {
	private static Singleton uniqueInstance;
 
	// other useful instance variables here
 
	private Singleton() {}
 
	public static synchronized Singleton getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}
 
	// other useful methods here
}


        Singleton.java

 

 

public class Singleton {
	private static Singleton uniqueInstance = new Singleton();;
 
	// other useful instance variables here
 
	private Singleton() {}
 
	public static Singleton getInstance() {
		return uniqueInstance;
	}
 
	// other useful methods here
}

 

 

二、解析

      1、第一种单件模式,在多线程时需要同步,造成了额外开销。

       2、第二种不用同步。


 

相关文章:

  • 2021-12-21
  • 2021-09-07
  • 2021-07-29
  • 2021-05-25
  • 2021-09-16
  • 2021-07-25
  • 2021-04-23
  • 2021-11-01
猜你喜欢
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2021-12-15
  • 2021-04-13
  • 2022-12-23
相关资源
相似解决方案