Java并发-线程基础( 三 )

线程局部变量JavaThreadLocal类可用于创建其值只能由同一线程访问的变量 。 因此 , 即使两个线程正在执行相同的代码 , 并且该代码具有对相同ThreadLocal变量的引用 , 两个线程也无法看到彼此的ThreadLocal变量 。
public class Main {public static class ThreadLocalStorage {private static final ThreadLocal threadLocal = new ThreadLocal<>();public static void setName(String name) {threadLocal.set(name);}public static String getName() {return threadLocal.get();}}public static void main(String[] args) {ThreadLocalStorage.setName("Main thread");Runnable runnable = () -> {ThreadLocalStorage.setName(getCurrentThreadName());try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Thread: [" + getCurrentThreadName() + "] " +"- value: [" + ThreadLocalStorage.getName() + "]");};Thread thread1 = new Thread(runnable);Thread thread2 = new Thread(runnable);thread1.start();thread2.start();System.out.println("Main exits");}private static String getCurrentThreadName() {return Thread.currentThread().getName();}}如果运行代码 , 我们可以看到每个线程都有其自己的ThreadLocal对象副本 。
Main exitsThread: [Thread-0] - ThreadLocal value: [Thread-0]Thread: [Thread-1] - ThreadLocal value: [Thread-1]【Java并发-线程基础】而不是每个线程在a内都有其自己的值ThreadLocal , 而是InheritableThreadLocal授予对线程以及该线程创建的所有子线程的值的访问权限 。