zoukankan      html  css  js  c++  java
  • 关于ThreadLocal的一道面试题

     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()的操作,这就会出现空指针了。

  • 相关阅读:
    基于python的种子搜索网站(三)项目部署
    Python 的 Geth 封装库 PyGeth
    主题: 002.04 Tkinter 星空大战
    python 打飞机项目 (实战一)
    python使用mysql的一些坑
    Python 变量与运算符
    字符流
    IO字节流(2)
    端口转发
    IO流(1)
  • 原文地址:https://www.cnblogs.com/zhuzhen/p/13344563.html
Copyright © 2011-2022 走看看