【问题标题】:ThreadLocal variable is null between Thread and RunnableThread 和 Runnable 之间的 ThreadLocal 变量为空
【发布时间】: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


    【解决方案1】:

    您只能在设置它的线程中看到 ThreadLocal 的值。在您的代码中,您在线程主线程中设置 ThreadLocal 并在另一个线程 - CustomThread 中读取它。

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 2012-09-24
      相关资源
      最近更新 更多