1、ThreadLocal
Thread类中有一个threadLocals字段,它是ThreadLocal内部类ThreadLocalMap类型。
- ThreadLocal的set方法:操作当前线程的threadLocals,以ThreadLocal.this为键,将值保存到Thread.threadLocals中
- ThreadLocal的get方法:取出当前线程的threadLocals中以ThreadLocal.this为键的值
//ThreadLocal.java public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } 复制代码
ThreadLocal构造函数,可指定保存的数据类型,以及重写initialValue设置初始值。之后就可以在不同线程中使用threadLocal的set、get方法,保存此数据类型的数据了。
//EventBus.java private final ThreadLocalcurrentPostingThreadState = new ThreadLocal () { @Override protected PostingThreadState initialValue() { return new PostingThreadState(); } };复制代码