其他分享
首页 > 其他分享> > ThreadLocal的一道有意思的题

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

标签:有意思,TestThreadLocalNpe,get,threadLocal,long,一道,ThreadLocal,static,public
来源: https://www.cnblogs.com/juniorMa/p/15205158.html