Java并发编程 - 一段代码解释 ThreadLocal 特性

/**
 * @author Lux Sun
 * @date 2020/9/10
 */
public class demo implements Runnable {

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

    @Override
    public void run() {
        System.out.println(threadLocal.get()); // null
        threadLocal.set("thread-2");
    }

    public static void main(String[] args) throws InterruptedException {
        threadLocal.set("thread-1");
        new Thread(new demo()).start();
        Thread.sleep(2000);
        System.out.println(threadLocal.get()); // thread-1
    }
}

输出

null
thread-1

你可能感兴趣的:(#,并发,&,线程,Java,并发编程,ThreadLocal,多线程,高并发)