ThreadLocal对象通常用于防止对可变的单实例变量或全局变量进行共享。
package com.lxc.tet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class MyThreadLocal<T> { private Map<Thread,T> map = new ConcurrentHashMap<Thread, T>(); protected T initialValue(){ return null; } public void set(T value){ map.put(Thread.currentThread(), value); } public T get(){ T result = null; result = map.get(Thread.currentThread()); if(result==null && !map.containsKey(Thread.currentThread())){ result=initialValue(); set(result); } return result; } public void remove(){ map.remove(Thread.currentThread()); } }