ThreadLocal 变量在 Thread 和 Runnable 之间为 null
ThreadLocal variable is null between Thread and Runnable
我为应用程序的每个传入请求使用一个 线程。起初,我通过 MDC class 在 SLF4J 中在 Thread 的构造函数中设置了一个标志,并在 Runnable 的 运行 方法,但值为空。我猜这个问题与 MDC class 有关所以我本来打算使用 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
还有什么需要我做的吗?
您只能在设置它的线程中看到ThreadLocal 的值。在您的代码中,您在主线程中设置 ThreadLocal 并在另一个线程中读取它 - CustomThread。
我为应用程序的每个传入请求使用一个 线程。起初,我通过 MDC class 在 SLF4J 中在 Thread 的构造函数中设置了一个标志,并在 Runnable 的 运行 方法,但值为空。我猜这个问题与 MDC class 有关所以我本来打算使用 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
还有什么需要我做的吗?
您只能在设置它的线程中看到ThreadLocal 的值。在您的代码中,您在主线程中设置 ThreadLocal 并在另一个线程中读取它 - CustomThread。