public class Singleton { private static EagerSingleton instance = new EagerSingleton(); private Singleton() { //私有構造函數 } public static EagerSingleton getInstance() { return instance; } }b. 懶漢式
public class SingletonClass{ private static SingletonClass instance=null; private SingletonClass(){} public static SingletonClass getInstance(){ if(instance==null){ instance=new SingletonClass(); } } return instance; } }// 懶漢式---不存在線程安全問題------效率比較低
public class SingletonClass{ private static SingletonClass instance=null; private SingletonClass(){} public static synchronized SingletonClass getInstance(){ if(instance==null){ instance=new SingletonClass(); } } return instance; } }// 懶漢式---不存在線程安全問題-----效率高
public class SingletonClass{ private static SingletonClass instance=null; private SingletonClass(){} public static SingletonClass getInstance(){ if(instance==null){ synchronized(SingletonClass.class){ if(instance==null){ instance=new SingletonClass(); } } } return instance; } }說明:synchronized方法與synchronized代碼快的區別
7. 線程安全與CPU核數有關嗎? java
無關,只是在單核狀況下,有些問題復現機率更低。 web