首页 > 其他分享 >记录构造方法ThreadLocal赋值失败---

记录构造方法ThreadLocal赋值失败---

时间:2023-01-19 15:36:25浏览次数:44  
标签:execute set 构造方法 System T1 --- ThreadLocal str public

省流:构造方法在主线程里跑的

先贴代码

public class Test {

    @SneakyThrows
    public static void main(String[] args) {
        ExecutorService execute = Executors.newSingleThreadExecutor();
        execute.execute(new T1("once"));
        execute.execute(new T1(null));
        Thread.sleep(1000);
        execute.shutdownNow();
    }

    static class T1 implements Runnable {
        static final ThreadLocal<String> str = new ThreadLocal<>();

        @SneakyThrows
        public T1(String a) {
            if (a != null){
                str.set(a);
                System.out.println("set str");
            }
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getId());
            System.out.println(str.get());
        }
    }

}

期望输出:

set str
线程id
once
线程id
null

实际输出:

 

 问题分析步骤:

debug分析 摇人最快

@SneakyThrows
        public T1(String a) {
            if (a != null){
                System.out.println(Thread.currentThread().getId());
                str.set(a);
                System.out.println("set str");
            }
        }

在这打印下线程号,执行一下问题就知道了

 

标签:execute,set,构造方法,System,T1,---,ThreadLocal,str,public
From: https://www.cnblogs.com/chiangkkk/p/17061572.html

相关文章

  • 37-ElasticSearch-Mapping映射
    1)、字段类型2)、映射3)、新版本改变1、创建映射2、添加新的字段映射其中index表示这个字段是否能被当作检索字段。(即通过employee-id无法进行查找)3、更新......
  • 【学懂Java】(四)面向对象编程-2
    一.局部变量和成员变量局部变量成员变量(全局变量)定义在方法中定义在方法外,类之内的变量栈内存中堆内存中局部变量没有默认值成员变量有默认值当前方法当前类的方法不同的方......
  • Python - requests 使用记录
    requests使用简单方法记录importrequestsfromfake_useragentimportUserAgentua=UserAgent()headers={'User-Agent':ua.random#伪装}#......
  • django-rest-swagger
    在日常工作中,程序员最苦恼的事情大概就是写文档了吧,虽然文档能够利于程序的传承,但是由于业务口径频繁变更,导致维护文档也变成了一件费时又费力的事情。因此,如果能够自动生......
  • drf-spectacular
    介绍drf-spectacular是为DjangoRESTFramework生成合理灵活的OpenAPI3.0模式。它可以自动帮我们提取接口中的信息,从而形成接口文档,而且内容十分详细,再也不用为写接口文......
  • Golang的基本数据类型-基本使用
    基本数据类型-基础使用数值型整数类型使用细节Golang各整数类型分:有符号和无符号,intuint的大小和系统是32位还是64位有关Golang的整型默认声明为int型如何......
  • 36-ElasticSearch-aggregations(执行聚合)
    聚合提供了从数据中分组和提取数据的能力。最简单的聚合方法大致等于SQLGROUPBY和SQL聚合函数。在Elasticsearch中,您有执行搜索返回hits(命中结果),并且同时返回聚......
  • AI换脸实战教学(FaceSwap的使用)---------第二步Tools:处理输入数据集。
    续上篇:https://www.cnblogs.com/techs-wenzhe/p/12936809.html第一步中已经提取出了源视频的人脸照片以及对应人脸遮罩(landmark以及其他自选遮罩)第二步:利用Tools处理提......
  • 35-ElasticSearch-进阶检索的基本操作
    1、SearchAPI2、QueryDSL1)、基本语法格式2)、返回部分字段3)、match【匹配查询】4)、match_phrase【短语匹配】也可以用关键字.keyword进行精确匹配,他与短语......
  • 53-HAProxy-常用高级功能及生产案例
    基于Cookie的会话保持cookievalue:为当前server指定cookie值,实现基于cookie的会话黏性注意:不支持tcpmode,使用httpmode-->属于七层协议案例:#配置选项cookiename[r......