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(); }
2、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); }
ThreadLocal的缺点
只能在当前线程生效,如果你在当前线程新创建的一个线程,新的线程就无法获取父线程设置的值。比如:
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassThreadLocalDefectDemo{ privatestatic ThreadLocal<String> threadLocal = new ThreadLocal<>();
// 子线程 new Thread(() -> { // 输出为"threadLocal做不到的事" System.out.println(inheritableThreadLocal.get()); }).start();
// 线程池复用 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("ProcessMessage-pool-%d").build(); ExecutorService executorService = new ThreadPoolExecutor(1, 1, 2000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
// 线程池复用 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("ProcessMessage-pool-%d").build(); ExecutorService executorService = new ThreadPoolExecutor(1, 1, 2000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
Future<?> submit = executorService.submit(() -> {
System.out.println(infoInheritableDataThreadLocal.get().getNormalMessage()); System.out.println(infoInheritableDataThreadLocal.get().getUserDetailInfo().getInnerMessage()); // 其他线程修改数据会影响到其他线程 infoInheritableDataThreadLocal.get().setUserDetailInfo(null); }); Object o = submit.get();
// 线程池复用 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("ProcessMessage-pool-%d").build(); ExecutorService executorService = new ThreadPoolExecutor(1, 1, 2000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());