java多线程-4-ThreadLocal

2019-09-30  本文已影响0人  宠辱不惊的咸鱼

概述

用例

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

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);
}
// 这个代码导致,当定义了多个ThreadLocal时,threadLocalHashCode会按HASH_INCREMENT增量累增
private final int threadLocalHashCode = nextHashCode();
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}
上一篇 下一篇

猜你喜欢

热点阅读