ThreadLocal
threadlocal 线程变量,每个线程都有单独的变量。用于线程之间的隔离。
ThreadLocal 使用
public class TestThread {
static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->0);
static List<Thread> ths = new ArrayList<>();
public static void main(String[] args) {
for (int i = 0; i < 50; i++) {
ths.add(new Thread(new Runnable() {
@Override
public void run() {
threadLocal.set(threadLocal.get()+1); // 设置当前线程值
System.out.println(Thread.currentThread().getName()+":"+threadLocal.get()); //获取线程值
}
}));
}
for (Thread th : ths) {
th.start();
}
}
}
ThreadLocal 中 变量
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal 中 set 方法
public void set(T value) {
Thread t = Thread.currentThread(); //获取当前线程引用
ThreadLocalMap map = getMap(t); // 获取当前线程的 ThreadLocalMap
if (map != null)
map.set(this, value); //当前存在,设置值
else
createMap(t, value); //当前不存在,创建并设置值
}
ThreadLocal 中 get 方法
public T get() {
Thread t = Thread.currentThread(); //获取当前线程引用
ThreadLocalMap map = getMap(t); // 获取当前线程的 ThreadLocalMap
if (map != null) { //取值返回
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue(); //初始化 ThreadLocalMap
}
//初始化 当前线程的 ThreadLocalMap
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;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap 为 ThreadLocal的内部类
static class ThreadLocalMap {
private Entry[] table;//数据数组
private int size = 0;//数组大小
private int threshold; //临界值
private static final int INITIAL_CAPACITY = 16; //默认大小
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value; //存储线程值
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 初始化
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
}
网友评论