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

  • 相关阅读:
    修改SharePoint 2013中item Created by 信息
    用powershell批量新增user profile
    如何发一封回复的时候收件人和发件人不同的邮件
    SharePoint 2013配置 Workflow Manager
    正则表达式
    go
    HTML5
    js-example
    css3
    jquery-example
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15205158.html
Copyright © 2011-2022 走看看