子线程中获取父线程的数据(线程池下失效)

发布时间 2023-04-06 14:18:36作者: java架构师1

子线程中获取父线程的数据

    static InheritableThreadLocal<String> local = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        local.set("123");
        System.out.println(Thread.currentThread().getName() + " ======= " + local.get());
        try {
            Thread thread = new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " ======= " + local.get());
                local.set("456");
                System.out.println(Thread.currentThread().getName() + " ======= " + local.get());
            },"child");
            thread.start();
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " ======= " + local.get());
    }