【发布时间】:2017-09-23 03:54:22
【问题描述】:
我为应用程序的每个传入请求使用一个线程。起初,我通过SLF4J中的MDC类在Thread的构造函数中设置了一个标志,并在Runnable的run方法中获取它,但值为null。我猜这个问题与 MDC 类有关,所以我打算使用最初的 ThreadLocal 可能性而不是 SLF4J 但是我错了,代码有还没有正常工作。 我的代码是:
public class CustomThread extends Thread
{
public static ThreadLocal<String> status = new ThreadLocal<String>();
public CustomThread(CustomRunnable target)
{
super(target);
status.set("Start");
}
}
public class CustomRunnable implements Runnable
{
public void run()
{
System.out.println(CustomThread.status.get());
}
}
public static void main(String[] args) throws InterruptedException
{
CustomThread t1 = new CustomThread(new CustomRunnable());
t1.start();
}
结果是:
The flag is : null
我还有什么需要做的吗?
【问题讨论】:
标签: java multithreading thread-safety thread-local