ThreadLocal和InheritableThreadLocal

2023-12-13 04:18:14

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

文章来源:https://blog.csdn.net/qq_19891197/article/details/134923358
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。