1 public class TestThreadLocalNpe {
 2     private static ThreadLocal<Long> threadLocal = new ThreadLocal();
 3 
 4     public static void set() {
 5         threadLocal.set(1L);
 6     }
 7 
 8     public static long get() {
 9         return threadLocal.get();
10     }
11 
12     public static void main(String[] args) throws InterruptedException {
13         new Thread(() -> {
14             set();
15             System.out.println(get());
16         }).start();
17         // 目的就是为了让子线程先运行完
18         Thread.sleep(100);
19         System.out.println(get());
20     }
21 }

问:上面这段代码会输出什么?为什么?

答:

1
Exception in thread "main" java.lang.NullPointerException
 at com.chentongwei.study.thread.TestThreadLocalNpe.get(TestThreadLocalNpe.java:16)
 at com.chentongwei.study.thread.TestThreadLocalNpe.main(TestThreadLocalNpe.java:26)

为什么输出1然后空指针了?

输出1是没有任何问题的。那空指针是为什么呢?

因为这是两个线程,子线程和主线程。子线程设置1,主线程肯定拿不到啊。ThreadLocal是和线程息息相关的。

再说说为什么会空指针?

因为你的get方法用的是long而不是Long,get方法在未设置初始化值的时候,默认返回的书null。long是基本类型,而ThreadLocal里的泛型是Long,get却是基本类型,所以要进行拆箱操作,也就是进行

null.longValue()的操作,这就会出现空指针了。

 

posted on 2020-07-20 13:30  十七年蝉  阅读(464)  评论(0编辑  收藏  举报