實例講授Java並發編程之ThreadLocal類。本站提示廣大學習愛好者:(實例講授Java並發編程之ThreadLocal類)文章只能為提供參考,不一定能成為您想要的結果。以下是實例講授Java並發編程之ThreadLocal類正文
ThreadLocal類可以懂得為ThreadLocalVariable(線程部分變量),供給了get與set等拜訪接口或辦法,這些辦法為每一個應用該變量的線程都存有一份自力的正本,是以get老是前往以後履行線程在挪用set時設置的最新值。可以將ThreadLocal<T>視為 包括了Map<Thread,T>對象,保留了特定於該線程的值。
歸納綜合起來講,關於多線程資本同享的成績,同步機制采取了“以時光換空間”的方法,而ThreadLocal采取了“以空間換時光”的方法。前者僅供給一份變量,讓分歧的線程列隊拜訪,爾後者為每個線程都供給了一份變量,是以可以同時拜訪而互不影響。
模仿ThreadLocal
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SimpleThreadLocal<T> {
private Map<Thread, T> valueMap = Collections
.synchronizedMap(new HashMap<Thread, T>());
public void set(T newValue) {
valueMap.put(Thread.currentThread(), newValue); // ①鍵為線程對象,值為本線程的變量正本
}
public T get() {
Thread currentThread = Thread.currentThread();
T o = valueMap.get(currentThread); // ②前往本線程對應的變量
if (o == null && !valueMap.containsKey(currentThread)) { // ③假如在Map中不存在,放到Map中保留起來。
o = initialValue();
valueMap.put(currentThread, o);
}
return o;
}
public void remove() {
valueMap.remove(Thread.currentThread());
}
protected T initialValue() {
return null;
}
}
適用ThreadLocal
class Count {
private SimpleThreadLocal<Integer> count = new SimpleThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer increase() {
count.set(count.get() + 1);
return count.get();
}
}
class TestThread implements Runnable {
private Count count;
public TestThread(Count count) {
this.count = count;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i
+ "th\t" + count.increase());
}
}
}
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));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
輸入
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