标签:
public class Test { private ThreadLocal<String> stringThreadLocal = new ThreadLocal<>() ; private ThreadLocal<String> stringThreadLocal2 = new ThreadLocal<>() ; public void print() { System.out.println("threadName:" + Thread.currentThread().getName() + ",value:" + stringThreadLocal.get()); System.out.println("threadName:" + Thread.currentThread().getName() + ",value:" + stringThreadLocal2.get()); } public void setValue(String value) { stringThreadLocal.set(value); stringThreadLocal2.set(value + "——2"); } public static void main(String[] args) throws InterruptedException { Test test = new Test() ; test.setValue("test0"); test.print(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { test.setValue("test1"); test.print(); } }) ; thread1.start(); Thread.sleep(1000); test.print(); } }
threadName:main,value:test0 threadName:main,value:test0——2 threadName:Thread-0,value:test1 threadName:Thread-0,value:test1——2 threadName:main,value:test0 threadName:main,value:test0——2
public T get() { // 获取当前线程 Thread t = Thread.currentThread(); // 获取当前Thread的map ThreadLocalMap map = getMap(t); if (map != null) { // 获取当前ThreadLocal对象对应的entry ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } // 获取当前线程对应的map ThreadLocalMap getMap(Thread t) { return t.threadLocals; } public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
标签:
原文地址:http://www.cnblogs.com/sten/p/5777979.html