ThreadLocal相當於一個Map<Thread, T>,各線程使用自己的線程對象Thread.currentThread()作為鍵存取數據,但ThreadLocal實際上是一個包裝了這個Map,並且線程只能存取自己的數據,不能操作其它線程的數據。
代碼示例:
public static void main(String[] args) {
String[] names = new String[]{"A", "B", "C", "D", "E"};
for(int i=0; i<names.length; i++){
final String myName = names[i];
new Thread(){
public void run(){
name.set(myName);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
test();
}
}.start();
}
/*
運行結果:
Thread-0 -> 我的名字叫A
Thread-2 -> 我的名字叫C
Thread-1 -> 我的名字叫B
Thread-3 -> 我的名字叫D
Thread-4 -> 我的名字叫E
*/
}
private static ThreadLocal<String> name = new ThreadLocal<String>();
public static void test(){
System.out.println(Thread.currentThread().getName() + " -> 我的名字叫" + name.get());
}