图解ThreadLocal

发布时间 2023-06-05 23:33:15作者: bxdblog

ThreadLocalTest

public class ThreadLocalTest {

    public static void main(String[] args) {
        ThreadLocal threadLoal_1 = new ThreadLocal();
        new Thread(()->{
            threadLoal_1.set("hello t1");
            System.out.println(Thread.currentThread().getName()+":"+threadLoal_1.get());
        },"t1").start();

        new Thread(()->{
            threadLoal_1.set("hello t2");
            System.out.println(Thread.currentThread().getName()+":"+threadLoal_1.get());
        },"t1").start();

    }
}
控制台输出:
t1:hello t1
t1:hello t2

ThreadLocal#get()

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

图解