Java中的ThreadLocal和 InheritableThreadLocal

2024-10-09 11:12:10 浏览数 (1)

Java中的ThreadLocal和 InheritableThreadLocal

代码语言:javascript复制
package com.example.core.mydemo.java;

/**
 * output
 * Thread-0 ThreadLocal value :null
 * Thread-0 InheritableThreadLocal value :InheritableThreadLocal string
 */
public class ThreadLocalTest {
    public static void main(String[] args) {
        //主线程中赋值
        ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();

        InheritableThreadLocal<String> stringInheritableThreadLocal = new InheritableThreadLocal<>();

        stringThreadLocal.set("ThreadLocal string");
        stringInheritableThreadLocal.set("InheritableThreadLocal string");

        //子线程中分别打印两个变量的信息
        new Thread(() -> {
            System.out.println(
                    Thread.currentThread().getName()   " ThreadLocal value :"   stringThreadLocal.get());
            System.out.println(Thread.currentThread().getName()   " InheritableThreadLocal value :"
                      stringInheritableThreadLocal.get());
        }).start();


    }
}

在上面的测试代码中,主线程中创建了两个变量,类型分别为:ThreadLocal和InheritableThreadLocal 然后在主线程中创建了一个新的线程 在新的线程中,尝试获取他们的值 从打印信息可以看得出来 对于ThreadLocal获取的值为null,而对于InheritableThreadLocal则能够获取到值

0 人点赞