InheritableThreadLocal测试

InheritableThreadLocal

简介:

InheritableThreadLocal 扩展了 ThreadLocal 以提供从父线程到子线程的值继承.
当创建子线程时,子线程将接收父线程具有值的所有可继承线程局部变量的初始值。

特征:

子线程可以从父线程到子线程的值继承.拷贝了一份新的值

实验:

验证子线程是否继承了父线程的值,并且验证子线程修改继承的值,是否对父线程有影响

结果:

子线程可以继承父线程的值,并且子线程修改继承的值不会影响父线程的变量

实验代码:
public class T02_InheritableThreadLocal {

    private static InheritableThreadLocal threadLocal = new InheritableThreadLocal<>();

    void m() {
        Integer integer = threadLocal.get();
        System.out.println("继承的父线程的值:" + integer);
        threadLocal.set(20000);
        System.out.println("修改threadLocal之后的值:" + threadLocal.get());
    }

    public static void main(String[] args) throws InterruptedException {
        T02_InheritableThreadLocal testMain = new T02_InheritableThreadLocal();

        threadLocal.set(1000);
        System.out.println("父线程threadLocal的值:" + threadLocal.get());
        System.out.println("子线程运行:");
        Thread thread = new Thread(() -> testMain.m());
        Thread thread2 = new Thread(() -> testMain.m());
        thread.start();
        thread2.start();
        thread.join();
        thread2.join();
        System.out.println("父线程threadLocal的值:" + threadLocal.get());
    }
}

实验结果:
image.png

你可能感兴趣的:(InheritableThreadLocal测试)