單例模式有不少種,我只說兩種最有表明性的。安全
package volati; /** * Created by lhw on 16-7-29.這種屬於懶加載,線程安全 */ public class Demo1 { private static Demo1 demo1; private Demo1() { } public static synchronized static Demo1 getDemo() ; if(demo1==null) demo1 =new Demo1(); return demo1; } }
-----多線程
package volati; /** * Created by lhw on 16-7-29.類加載時初始化類 */ public class Demo2 { private static Demo2 demo2 = new Demo2(); private Demo2() { } public static Demo2 getDemo2() { return demo2; } }
--------------ide
package volati; /** * Created by lhw on 16-7-29.這種狀況的單利用於多線程的數據隔離。即每一個線程都有惟一的demo3。 */ public class Demo3 { public static ThreadLocal<Demo3> instance = new ThreadLocal<Demo3>(){ @Override protected Demo3 initialValue() { return new Demo3(); } }; public static Demo3 getInstance(){ return instance.get(); } }