すべてのスレッドに共通のThreadLocal初期値を設定しました。コンストラクターを呼び出すときに値を変更し、正しく印刷しました。しかし、スレッドを開始するとき、再び初期値に変更されましたか?それは期待されていますか?はいの場合、説明は何ですか?以下は私の2つのクラスです。前もって感謝します。ThreadLocal InitialValueが2回呼び出されました
MyRunnableThreadLocal.java
public class MyRunnableThreadLocal implements Runnable { private ThreadLocal<String> threadLocal = new ThreadLocal<String>(){ @Override protected String initialValue() { return "Thread Name not set yet"; } }; public MyRunnableThreadLocal(String threadName) { System.out.println(threadLocal.get()); threadLocal.set(threadName); System.out.println("Thread name: " + threadLocal.get()); } @Override public void run() { System.out.println(threadLocal.get()); threadLocal.set(threadLocal.get() + " " + (Math.random() * 100D)); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println(threadLocal.get()); } }
ThreadLocalTest.java
public class ThreadLocalTest { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnableThreadLocal("Thread 1")); Thread t2 = new Thread(new MyRunnableThreadLocal("Thread 2")); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
出す:
Thread Name not set yet
Thread name: Thread 1
Thread Name not set yet
Thread name: Thread 2
Thread Name not set yet
Thread Name not set yet
Thread Name not set yet 20.24825634584746
Thread Name not set yet 59.67633602373702
ありがとう@Peter。まだ私はいくつかの混乱があります。スレッドローカル値の設定はどうですか?最初の4行がメインスレッドで実行されている場合、#2行は#3行に反映されていませんか?最初の** MyRunnableThreadLocal **オブジェクトで作業している場合、なぜそれが行番号5または6に反映されていないのですか? –
@Peterに感謝します。私はそのコンセプトを得た。また、InheritableThreadLocalとThreadLocalの違いがわかりました。 http://geekexplains.blogspot.in/2009/02/threadlocal-inheritablethreadlocal-in.html 誰かがそれを探している場合。 –
@AnirbanB興味深いClassValueもあります。スレッドの代わりにクラスの場合も同様です。スレッドローカルバッファとして使用するために、ThreadLocalsが 'static'であることは珍しいことではありません。 –