public class ThreadLocalId { private static final AtomicLong nextId = new AtomicLong(0); private static final ThreadLocal<Long> TL = ThreadLocal.withInitial( () -> nextId.getAndIncrement()); // 为每个线程分配一个唯一的ID private static long get() { return TL.get(); } }
public class SafeDateFormat { private static final ThreadLocal<DateFormat> TL = ThreadLocal.withInitial( () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); private static DateFormat get() { return TL.get(); } }
public class Thread implements Runnable { // 线程内部持有ThreadLocalMap ThreadLocal.ThreadLocalMap threadLocals = null; } public class ThreadLocal<T> { public T get() { // 获取当前线程持有的ThreadLocalMap Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { // 在ThreadLocalMap中查找变量 ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } static class ThreadLocalMap { // 内部是数组而不是Map private Entry[] table; // 根据ThreadLocal查找Entry private Entry getEntry(ThreadLocal<?> key) { } static class Entry extends WeakReference<ThreadLocal<?>> { Object value; } } }
private static final ExecutorService pool = Executors.newFixedThreadPool(1); private static final ThreadLocal<Object> TL = ThreadLocal.withInitial(() -> new Object()); public static void main(String[] args) { pool.execute(() -> { try { TL.set(new Object()); } finally { // 手动清理ThreadLocal TL.remove(); } }); }
转载请注明出处:http://zhongmingmao.me/2019/05/20/java-concurrent-thread-local/
访问原文「 Java并发 -- ThreadLocal模式 」获取最佳阅读体验并参与讨论