ThreadLocal对象通常用于防止对可变的单实例变量或全局变量进行共享。
精简版:
public class MyThreadLocal<T> { private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>()); public void set(T newValue) { map.put(Thread.currentThread(), newValue); } public T get() { return map.get(Thread.currentThread()); } public void remove() { map.remove(Thread.currentThread()); } }
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()); } }