再說說單例模式和多執行緒(靜態內部類實現)
阿新 • • 發佈:2018-12-26
靜態內部類:
package thread.singleton;
public class StaticInnerClassSingleton {
private static class Singleton{
private static Singleton singleton = new Singleton();
}
public Singleton getInstance(){
return Singleton.singleton;
}
}
使用雙重if判斷+synchronized:
package thread.singleton; public class SynchronizedLazySingleton { private static SynchronizedLazySingleton lazySingleton; private SynchronizedLazySingleton(){} public static SynchronizedLazySingleton getInstance(){ //效率提高,避免後續執行緒都嘗試獲取鎖照成鎖競爭 if(lazySingleton == null){ try { //模擬共享物件初始化時間 //TimeUnit.SECONDS.sleep(1000); Thread.sleep(1000); synchronized (SynchronizedLazySingleton.class) { //在進入sychronzied方法體後,如果不進行if判斷,會引發執行緒安全問題 if(lazySingleton == null){ lazySingleton = new SynchronizedLazySingleton(); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return lazySingleton; } public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(SynchronizedLazySingleton.getInstance().hashCode()); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println(SynchronizedLazySingleton.getInstance().hashCode()); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println(SynchronizedLazySingleton.getInstance().hashCode()); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println(SynchronizedLazySingleton.getInstance().hashCode()); } }).start(); } }