zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Servlet Class4
    Servlet Class3
    Servlet Class2
    Servlet Class1
    HTTP基础知识
    XML基础知识
    JAVA Class25
    JAVA Class24
    JAVA Class23
    JAVA Class22
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15205158.html
Copyright © 2011-2022 走看看