线程本地存储(线程本地变量)可以使相同变量的每个不同的线程都创建不同的存储。因此,如果有5个线程都使用同一个变量V所表示的对象,那线程本地存储就会生成5个用于V的不同的存储块,它们使得你可以将状态与线程关联起来。通过查看源码可以发现,其内部实现是通过一个叫ThrealLocalMap来做的,每个线程都有一个ThreadLocalMap,每个线程的ThreadLocalMap对象可以用来保存每个线程运行时的线程本地变量值。
【示例代码】
package test.demo.threadlocal;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadLocalHolder {
private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
private Random rand = new Random(47);
protected synchronized Integer initialValue() {
return rand.nextInt(10000);
}
};
public static void increment() {
value.set(value.get() + 1);
}
public static int get() {
return value.get();
}
public static void main(String[] args) throws InterruptedException {
System.out.println("*****************************************");
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
exec.execute(new Accessor(i));
}
TimeUnit.MILLISECONDS.sleep(50);
exec.shutdownNow();
}
}
package test.demo.threadlocal;
public class Accessor implements Runnable {
private final int id;
public Accessor(int id) {
this.id = id;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
ThreadLocalHolder.increment();
System.out.println(this);
Thread.yield();
}
}
public String toString() {
return "#Thread[" + id + "] [ThreadLocal] value:" + ThreadLocalHolder.get();
}
}
【输出结果】
*****************************************
#Thread[0] [ThreadLocal] value:9259
#Thread[0] [ThreadLocal] value:9260
#Thread[0] [ThreadLocal] value:9261
#Thread[2] [ThreadLocal] value:556
#Thread[0] [ThreadLocal] value:9262
#Thread[2] [ThreadLocal] value:557
#Thread[0] [ThreadLocal] value:9263
#Thread[2] [ThreadLocal] value:558
#Thread[0] [ThreadLocal] value:9264