ThreadLocal用法

用法

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

示例

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

复制代码

结果:ide

解析

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

先看set方法ui

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方法this

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里面的值是同样的,不一样线程之间互不干扰,这样就达到了同一个线程中值的传递spa

相关文章
相关标签/搜索