ThreadLocal的一道有意思的题

public class TestThreadLocalNpe {
    private static ThreadLocal<Long> threadLocal = new ThreadLocal();

    public static void set() {
        threadLocal.set(1L);
    }

    public static long get() {
        return threadLocal.get();
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            set();
            System.out.println(get());
        }).start();
        // 目的就是为了让子线程先运行完
        Thread.sleep(100);
        System.out.println(get());
    }
}

这段代码的输出是

1
Exception in thread "main" java.lang.NullPointerException
    at org.example.threadlocalrandom.TestThreadLocalNpe.get(TestThreadLocalNpe.java:16)
    at org.example.threadlocalrandom.TestThreadLocalNpe.main(TestThreadLocalNpe.java:26)

注意get()方法

 public static long get() {
        return threadLocal.get();
    }

long是基本类型,主线程ThreadLocal.get()返回的是null,由于要把Long转成long,所以做了一次拆箱。null.longValue

上一篇:深入理解Python中的ThreadLocal变量(上)


下一篇:Java 线程安全