有人能告诉我为什么threadlocal.get()在我使用ScheduledExecutorService启动线程时给我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();
}
}
}发布于 2015-04-20 07:44:03
ThreadLocal<String> local = new ThreadLocal<String>();
local.set("String");
System.out.println(local.get());您需要在ThreadLocalVariable中设置一些东西,然后检索它。最初,ThreadLocal是空的。
发布于 2015-04-20 07:43:16
因为指定的ThreadLocal变量为空。您需要设置一个值或指定一个初始值。
ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "initial value");或
ThreadLocal<String> threadLocal = new ThreadLocal<>(); // now holding null
threadLocal.set("value"); //now holding "value"如果不设置值,则ThreadLocal默认为null。
发布于 2015-04-20 07:43:39
应该在方法运行之外初始化本地线程。您只初始化一次,然后从线程内部使用.set()和.get()。不要使用多个本地线程实例。
https://stackoverflow.com/questions/29741689
复制相似问题