ThreadLocal類可以理解為ThreadLocalVariable(執行緒區域性變數),提供了get與set等訪問介面或方法,這些方法為每個使用該變數的執行緒都存有一份獨立的副本,因此get總是返回當前執行執行緒在呼叫set時設定的最新值。可以將ThreadLocal
概括起來說,對於多執行緒資源共享的問題,同步機制採用了“以時間換空間”的方式,而ThreadLocal採用了“以空間換時間”的方式。前者僅提供一份變數,讓不同的'執行緒排隊訪問,而後者為每一個執行緒都提供了一份變數,因此可以同時訪問而互不影響。
模擬ThreadLocal
複製程式碼 程式碼如下:
import ections;
import Map;
import ;
public class SimpleThreadLocal
private Map
hronizedMap(new HashMap
public void set(T newValue) {
(entThread(), newValue); // ①鍵為執行緒物件,值為本執行緒的變數副本
}
public T get() {
Thread currentThread = entThread();
T o = (currentThread); // ②返回本執行緒對應的變數
if (o == null && !ainsKey(currentThread)) { // ③如果在Map中不存在,放到Map中儲存起來。
o = initialValue();
(currentThread, o);
}
return o;
}
public void remove() {
ve(entThread());
}
protected T initialValue() {
return null;
}
}
實用ThreadLocal
複製程式碼 程式碼如下:
class Count {
private SimpleThreadLocal
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer increase() {
(() + 1);
return ();
}
}
class TestThread implements Runnable {
private Count count;
public TestThread(Count count) {
t = count;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 3; i++) {
tln(entThread()ame() + "t" + i
+ "tht" + ease());
}
}
}
public class TestThreadLocal {
public static void main(String[] args) {
Count count = new Count();
Thread t1 = new Thread(new TestThread(count));
Thread t2 = new Thread(new TestThread(count));
Thread t3 = new Thread(new TestThread(count));
Thread t4 = new Thread(new TestThread(count));
t();
t();
t();
t();
}
}
輸出
複製程式碼 程式碼如下:
Thread-0 1th 1
Thread-0 2th 2
Thread-0 3th 3
Thread-3 1th 1
Thread-1 1th 1
Thread-1 2th 2
Thread-2 1th 1
Thread-1 3th 3
Thread-3 2th 2
Thread-3 3th 3
Thread-2 2th 2
Thread-2 3th 3