ThreadLocal 的功能是设置每个 Thread 的变量。
Thread 有个如下变量:
Thread ------> ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocalMap的构造函数:
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);
}
ThreadLocalMap 的 set 方法:
//以当前ThreadLocal对象为 key, 存入 value 值
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);
}
ThreadLocalMap 的 get 方法:
//以当前线程为 key,得到对应的ThreadLocalMap, 再以当前线程的 ThreadLocal为key, get 出 Entry,返回其 value 值
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this );
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
一个例子如下:
package com.colorcc.multi.thread.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalClient {
//变量命名直观的表示了一个对象,如需要其他对象,则可创建新的 threadLocal,如 userThreadLoal, userThreadLocal
ThreadLocal<AtomicInteger> atomicThreadLocal = new ThreadLocal<AtomicInteger>() {
public AtomicInteger initialValue() {
return new AtomicInteger(0);
}
};
public static void main(String[] args) {
ThreadLocalClient tlc = new ThreadLocalClient();
tlc.testThreadLocal();
}
private void testThreadLocal() {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 8; i++) {
executor.execute(new Runnable() {
public void run() {
// set / get 都 default 的使用了当前 thread作为 map 的 key
atomicThreadLocal.set (new AtomicInteger(atomicThreadLocal.get() .incrementAndGet()));
System.out.println(Thread.currentThread().getName() + " : " + atomicThreadLocal.get());
}
});
}
}
}
一种输出结果如下:
pool-1-thread-1 : 1
pool-1-thread-2 : 1
pool-1-thread-2 : 2
pool-1-thread-2 : 3
pool-1-thread-1 : 2
pool-1-thread-2 : 4
pool-1-thread-2 : 5
pool-1-thread-1 : 3
可以看到两个线程互不影响。