转载

ThreadLocal理解

ThreadLocal 的内部类。是以 ThreadLocal 的 hash 值为数组下标, Entry 元素为值的数组。ThreadLocalMap 内部是实现了一个类似 Map 的映射关系,内部的 Entry 继承自 WeakReference<ThreadLocal<?>> ,它持有ThreadLocal的弱引用,保存 ThreadLocal.set(value) 传入的 value

static class Entry extends WeakReference<ThreadLocal<?>> {
    /** The value associated with this ThreadLocal. */
    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        super(k);
        value = v;
    }
}
复制代码

ThreadLocal

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();
}
复制代码

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

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
复制代码

使用地方有:

  • Android的消息循环机制(Looper Handler MessageQueue)就是基于这个。
  • ...

实例:

public class Main {
    static final ThreadLocal<String> mThreadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        new Thread("thread1") {
            @Override
            public void run() {
                mThreadLocal.set("value1");
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(currentThread().getName() + " localValue:" + mThreadLocal.get());
            }
        }.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        new Thread("thread2") {
            @Override
            public void run() {
                mThreadLocal.set("value2");
                System.out.println(currentThread().getName() + " localValue:" + mThreadLocal.get());
            }
        }.start();

    }
}
复制代码

输出:

thread2 localValue:value2
thread1 localValue:value1
复制代码

虽然是同一个 ThreadLocal对象 ,而且都调用的同样的 set get 方法,但是 get 方法返回的值,一定是与当前线程对应的。

原文  https://juejin.im/post/5ca225adf265da30cd1847f3
正文到此结束
Loading...