懶漢式單例--雙重檢測鎖實現執行緒安全
阿新 • • 發佈:2018-11-25
Football2.java
/** * 懶漢式單例 * 用的時候再建立一個物件,執行緒不安全 * @author Administrator * */ class FootBall2 { private static int count; private static FootBall2 fb; private FootBall2(){ System.out.println("初始化" + (count++) + "次"); } public static FootBall2 getFootBall(){ if(fb == null){ synchronized (FootBall2.class) { if(fb == null){ fb = new FootBall2(); } } } return fb; } }
測試類SinglerTest2.j:
public class SinglerTest2 { public static void main(String[] args) { for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + ":" + FootBall2.getFootBall()); } }).start(); } } }
結果:
初始化0次
Thread-5:[email protected]
Thread-1:[email protected]
...