publicstaticvoidmain(String[] args){ final ThreadLocalTest test = new ThreadLocalTest();
new Thread(new Runnable() { @Override publicvoidrun(){ List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); test.setThreadLocal(list); test.getThreadLocal(); } },"t1").start();
new Thread(new Runnable() { @Override publicvoidrun(){ List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); test.setThreadLocal(list); test.getThreadLocal(); } },"t2").start(); } }
运行结果
1 2 3 4 5 6
t1###1 t1###2 t1###3 t2###a t2###b t2###c
ThreadLocal原理
set方法
1 2 3 4 5 6 7 8
publicvoidset(T value){ Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
get方法
1 2 3 4 5 6 7 8 9 10 11 12 13
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(); }