ThreadLocal和InheritableThreadLocal

1:InheritableThreadLocal变量传递(变量只能往子传递,不能子线程往父线程传递)

    @SneakyThrows
    public static void main(String[] args) {
        final ThreadLocal threadLocal = new InheritableThreadLocal();
        threadLocal.set("main");
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();
                threadLocal.set("线程1修改");
                System.out.println("线程1 =" + threadLocal.get());

            }
        };
        Thread t2 = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                super.run();
                System.out.println("线程2 =" + threadLocal.get());
            }
        };
        t.start();
        t2.start();
    }

1-1:打印结果

线程1 =线程1修改
线程2 =main

2:ThreadLocal变量隔离

    @SneakyThrows
    public static void main(String[] args) {
        final ThreadLocal threadLocal = new ThreadLocal();
        threadLocal.set("main");
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();
                threadLocal.set("线程1修改");
                System.out.println("线程1 =" + threadLocal.get());

            }
        };
        Thread t2 = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                super.run();
                System.out.println("线程2 =" + threadLocal.get());
            }
        };
        t.start();
        t2.start();
    }

2-1:打印结果

线程1 =线程1修改
线程2 =null

你可能感兴趣的:(java,开发语言)