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

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

    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());
    }

 

posted @ 2023-04-06 14:13  java架构师1  阅读(113)  评论(0)    收藏  举报