基于《java编程第四版》的相关代码
/**
* 线程本地存储
* 相当于为每个线程开启了一个map,存放属于自己的特有对象或者值
*/
public class ThreadLocalVariableHolder {
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 Exception{
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0 ; i < 5 ; i++){
exec.execute(new Access(i));
}
TimeUnit.MILLISECONDS.sleep(100);
exec.shutdownNow();
}
}
class Access implements Runnable{
private final int id;
public Access(int idn){
this.id = idn;
}
public void run() {
while (!Thread.currentThread().isInterrupted()){
ThreadLocalVariableHolder.increment();
System.out.println(this);
Thread.yield();
}
}
@Override
public String toString() {
return "#" + id + ':' + ThreadLocalVariableHolder.get();
}
}
1.线程(Thread)
/* 与此线程有关的ThreadLocal值。该映射由ThreadLocal类维护。*/ ThreadLocal.ThreadLocalMap threadLocals = null; |
2.ThreadLocal
(1)重写initialValue方法
private Random rand = new Random(47);
protected synchronized Integer initialValue(){
return rand.nextInt(10000);
}
(2)set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
(3)get方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);//获取当前线程对应的ThreadLocalMap
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
(4)其他方法
a.getMap方法
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
b.setInitialValue方法
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}