单例模式和ThreadLocal的用法及区别

单例模式有很多种,我只说两种最有代表性的。

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;
    }
}

--------------

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();
    }
}

 

posted on 2018-01-14 17:52  剑姬  阅读(531)  评论(0编辑  收藏  举报

导航