Java的高并发编程系列(七) ThreadLocal线程局部变量和线程安全的单例模式

ThreadLocal线程局部变量

public class ThreadLocal1 {

    volatile static Person p = new Person();

    public static void main(String[] args) {

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(p.name);
        }).start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            p.name = "lisi";
        }).start();
    }
}

class Person{
    String name = "zhangsan";
}

ThreadLocal是使用空间换时间,synchronized是使用时间换空间,比如在hibernate中session就存在与ThreadLocal中,避免synchronized的使用。

public class ThreadLocal2 {

    /*volatile static Person p = new Person();*/
    private static ThreadLocal tl = new ThreadLocal<>();

    public static void main(String[] args) {

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(tl.get());
        }).start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tl.set(new Person1());
        }).start();
    }
}

class Person1 {
    String name = "zhangsan";
}

ThreadLocal只对当前线程范围有效。


线程安全的单例模式:
阅读文章:http://www.cnblogs.com/xudong-bupt/p/3433643.html
更好的是采用下面的方式,既不用加锁,也能实现懒加载

public class Singleton {

    private Singleton(){
        System.out.println("single");
    }

    private static class Inner{
        private static Singleton s = new Singleton();
    }

    public static Singleton getSingleton(){
        return Inner.s;
    }

    public static void main(String[] args) {
        Thread[] ths = new Thread[200];
        for(int i=0; inew Thread(()->{
                Singleton.getSingleton();
            });
        }

        Arrays.asList(ths).forEach(o->o.start());
    }
}

你可能感兴趣的:(java)