I set the ThreadLocal initial value common for all threads. When calling constructor I changed the value and it printed correctly. But when starting the thread, it again changed to initial value? Is that expected? If yes, what is the explanation? Below is my two classes. Thanks in advance.
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(); } } }
Out Put:
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