程序员

ThreadLocal

2020-07-11  本文已影响0人  尉昌达

ThreadLocal,线程之间隔绝。

public class ThreadLocal2 {
    //volatile static Person p = new Person();
    static ThreadLocal<Person> tl = new ThreadLocal<>();
    
    public static void main(String[] args) {
                
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            System.out.println(tl.get());
        }).start();
        
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tl.set(new Person());
        }).start();
    }
    
    static class Person {
        String name = "zhangsan";
    }
}

输出:

null

上面代码,在一个线程中设置 tl.set(new Person()),在另一个线程中tl.get()的是null。
在ThreadLocal set方法里,

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

进入getMap

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

-- set的时候,是把值设置到了当前线程的map中,所以别的线程访问不到。

上一篇下一篇

猜你喜欢

热点阅读