2017-09-23 78 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。

相關問題