menu 李昊天的个人博客
ThreadLocal学习笔记
874 浏览 | 2021-04-07 | 分类:JAVA | 标签:java,线程

概述介绍

ThreadLocal是用来操作 Thread中的 threadLocals (threadLocals ThreadLocal 的内部类)

每个线程独占一个 threadLocals

每个线程可以有多个 ThreadLocal Thread中的threadLocals 是一个Map,以ThreadLocal作为Key来访问。

每个ThreadLocal只对应一个值,相当于直接从map中将值取出来。

Demo

每一个对于ThreadLocal 中的数据是独享的,起到了数据隔离的作用。synchronized是线程隔离。

代码

public class Demo {
    public  ThreadLocal<String> local = new ThreadLocal();

    public void set(String s){
        local.set(s);
    }

    public  String get(){
        return local.get();
    }
    public static void main(String[] args) {

        Demo demo = new Demo();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.set("第"+ finalI +"个");
                    System.out.println(demo.get());
                }
            }).start();
        }

    }
}

输出

五个 public 方法

返回值类型方法
Tget()返回当前线程的此线程局部变量的副本中的值。
protected TinitialValue()返回此线程局部变量的当前线程的“初始值”。
voidremove()删除此线程局部变量的当前线程的值。
voidset(T value)将当前线程的此线程局部变量的副本设置为指定的值。
static ThreadLocalwithInitial(Supplier supplier)创建线程局部变量。
   public T get() {
        // 获取当前的线程
        Thread t = Thread.currentThread();
        // 获得当前线程的threadLocals
        ThreadLocalMap map = getMap(t);
       // 当map为空的时候创建一个
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            // get的时候判断一下是否为空,
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
     ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
     void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    // 当get前没有set的时候调用此方法,返回initialValue的值默认是null
   private T setInitialValue() {
        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;
    }

set

set 的时候先从当前线程中取出 ThreadLocalMa 用自己即ThreadLocal作为key来寻找值,当不存在的时候调用createMap来创建map

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

     ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
     void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

发表评论

email
web

全部评论 (暂无评论)

info 还没有任何评论,你来说两句呐!