ThreadLocal用法

518 阅读2分钟

用法

ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量

示例

public class ThreadLocalTest {
    public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static String get() {
        return threadLocal.get();
    }

    public static void set(String value) {
        threadLocal.set(value);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            final int j = i;
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    ThreadLocalTest.set(j + "");
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + ThreadLocalTest.get());
                }
            });

            t.start();
        }
    }
}

结果:

解析

通过上述示例 最主要的和最常用的就是get和set方法

先看set方法

 public void set(T value) {
        //获取当前线程
        Thread t = Thread.currentThread();
        //获取当前线程的ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //如果map存在 直接设值
            map.set(this, value);
        else
            //如果不存在,创建一个map并设置初始值
            createMap(t, value);
    }

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

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
  1. Tread类会有一个ThreadLocal.ThreadLocalMap threadLocals = null;
  2. ThreadLocalMap 是ThreadLocal的内部类,其实就是一个map,key为当前ThreadLocal value为对应值

再看get方法

public T get() {
        //获取当前线程
        Thread t = Thread.currentThread();
        //获取当前线程的ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //如果ThreadLocalMap不为null 通过map获取对应的值
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        
        //如果没有得到对应的值,就初始化该ThreadLocal和对应的值
        return setInitialValue();
    }
    
    private T setInitialValue() {
        //初始化该ThreadLocal值
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }
    
    protected T initialValue() {
        return null;
    }

小结

从源码可以看出,每个线程都有自己的ThreadLocalMap,map里面的key为ThreadLocal,value为对应的值,所以ThreadLocal在每个线程中是互不干扰的,这样同一个线程取到ThreadLocal里面的值是一样的,不同线程之间互不干扰,这样就达到了同一个线程中值的传递