ThreadLocal 和 InheritableThreadLocal 的区别

发布时间 2023-05-23 09:30:31作者: 拾月凄辰

结论:同一个 ThreadLocal 变量不能在子线程中获取到,而 InheritableThreadLocal 变量中的值可以在父子线程之间传递。

例子:

public class Main {

    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    private static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        threadLocal.set("mainThread");
        inheritableThreadLocal.set("hello");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("threadLocal: " + threadLocal.get());    // null
                System.out.println("inheritableThreadLocal: " + inheritableThreadLocal.get());  // hello
            }
        });
        thread.start();
    }
}

输出:

threadLocal: null
inheritableThreadLocal: hello