2017-09-23 81 views
0

之间空我使用线程对于每个传入请求给应用程序。起初,我在SLF4J设置线程的构造标志由MDC类和Runnable的run方法获取它,但值为空。我猜想这个问题与MDC类有关,所以我原本打算使用ThreadLocal的可能性而不是SLF4J但是我错了,代码还没有正常工作。 我的代码是:ThreadLocal变量是线程和可运行

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 

还有什么,我有什么关系?

回答

0

只能在线程将它设定看到的ThreadLocal的价值。在你的代码在主线程的ThreadLocal设置在另一胎读它 - CustomThread。

相关问题