gpt4 book ai didi

java - ScheduledExecutorService 的 ThreadLocal

转载 作者:搜寻专家 更新时间:2023-11-01 02:42:58 24 4
gpt4 key购买 nike

有人可以告诉我为什么当我使用 ScheduledExecutorService 启动线程时 threadlocal.get() 给我 null 吗?

 public class ThreadTest extends ParentClassThread
{
private static ScheduledFuture<?> periodicFuture;
private static ScheduledExecutorService ex;

public ThreadTest(){
ex = Executors.newSingleThreadScheduledExecutor();
periodicFuture = ex.schedule(this, 1, TimeUnit.SECONDS);
}

@Override
public void run() {
try {
System.out.println("Thread started");
for (int i = 0; i <= 100000; i++) {
System.out.println(i);
}
ThreadLocal local = new ThreadLocal();
System.out.println(local.get());
}catch(Exception e){

}finally {
ex.shutdown();
}

}
}

最佳答案

ThreadLocal<String> local = new ThreadLocal<String>();
local.set("String");
System.out.println(local.get());

您需要在 ThreadLocalVariable 中设置一些内容,然后检索它。最初,ThreadLocal 是空的。

关于java - ScheduledExecutorService 的 ThreadLocal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29741689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com