1 ThreadLocal API
ThreadLocal类的三个方法:
- void set(T value):保存值;
- T get():获取值;
- void remove():移除值。
2 ThreadLocal的内部是Map
ThreadLocal内部其实是个Map来保存数据。虽然在使用ThreadLocal时只给出了值,没有给出键,其实它内部使用了当前线程做为键。
class MyThreadLocal<T> { private Map<Thread,T> map = new HashMap<Thread,T>(); public void set(T value) { map.put(Thread.currentThread(), value); }
public void remove() { map.remove(Thread.currentThread()); }
public T get() { return map.get(Thread.currentThread()); } } |