java多线程-4-ThreadLocal

概述

  • JDK 1.2出现
  • ThreadLocal为每个线程提供独立的变量副本
  • 从线程的角度看,目标变量就像是线程的本地变量,这也是类名中“Local”所要表达的意思

用例

public class TestNum {
    // 通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
        public Integer initialValue() {
            return 0;
        }
    };
    // 获取下一个序列值
    public int getNextNum() {
        seqNum.set(seqNum.get() + 1);
        return seqNum.get();
    }
    public static void main(String[] args) {
        TestNum sn = new TestNum();
        // 3个线程共享sn,各自产生序列号
        TestClient t1 = new TestClient(sn);
        TestClient t2 = new TestClient(sn);
        TestClient t3 = new TestClient(sn);
        t1.start();
        t2.start();
        t3.start();
    }
    private static class TestClient extends Thread {
        private TestNum sn;
        public TestClient(TestNum sn) {
            this.sn = sn;
        }
        public void run() {
            for (int i = 0; i < 3; i++) {
                // 每个线程打出3个序列值
                System.out.println("thread[" + Thread.currentThread().getName() + "] --> sn["+ sn.getNextNum() + "]");
            }
        }
    }
}

ThreadLocal类方法

  • void set(Object value):设值
  • public Object get():取值
  • public void remove():移除值
  • JDK 5.0新增;线程结束后,对应该线程的局部变量将自动被垃圾回收,显式调用该方法并不是必须的,但可以加快内存回收
  • protected Object initialValue():初始值
  • 延迟调用方法,在线程第1次调用get()或set(Object)时执行,仅执行1次
  • 缺省实现返回null
  • JDK5.0中,ThreadLocal已支持泛型,类名变为ThreadLocal<T>;新版本API方法是void set(T value)、T get()以及T initialValue()

ThreadLocal类解析

// 内部类ThreadLocalMap,作为Thread的属性
static class ThreadLocalMap
// 根据t拿map(直接返回t的属性)
// 根据map拿Entry(根据ThreadLocal对象hash属性定位table数组元素entry,然后比对entry.get()与ThreadLocal相等)
// entry的value属性就是所要的值
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();
}
// 根据t拿map
// 如果是第一次,就创建map,创建Entry(ThreadLocal, value),并将map赋给Thread
// 如果不是第一次,就给map赋值
// 赋值时,map的table每个索引位置只有一个Entry,而这个索引 = ThreadLocal.threadLocalHashCode & (table.length - 1)
// 碰撞时,直接轮训table,找下一个空位塞值
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}
  • 神奇的threadLocalHashCode属性(个人小菜鸟一枚,故由此感觉)
// 这个代码导致,当定义了多个ThreadLocal时,threadLocalHashCode会按HASH_INCREMENT增量累增
private final int threadLocalHashCode = nextHashCode();
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容