【07】單例VS多執行緒
阿新 • • 發佈:2018-12-01
還是套路問題,一種思想而已,兩種方式
1 dubble check instance
2 static inner class
兩次檢測加類鎖
靜態內部類,其實就是餓漢模式,直接給你就好了
package Concurrency; class dubbleCheck{ private static dubbleCheck ds ; public dubbleCheck getInstance(){ if(ds == null){ try{ Thread.sleep(View Code50); synchronized (dubbleCheck.class){ if(ds==null){ ds = new dubbleCheck(); } } }catch (InterruptedException e){ e.printStackTrace(); } } return ds; }protected dubbleCheck(){ } } class InnerSigleton { private static class Sigleton{ private static InnerSigleton is = new InnerSigleton(); } public static InnerSigleton getInstance(){ return Sigleton.is; } }