When I ran the code, I'm expecting the result to show
Thread-0 - hello-0
Thread-1 - hello-1
However, the first thread seems to be returning null. Where am I going wrong here?
public class MyThreadLocal extends Thread {
private static final ThreadLocal<String> testId = new InheritableThreadLocal<String>();
public MyThreadLocal(String testId) {
this.testId.set(testId);
}
public void run() {
int loop = 10;
for (int i=0;i<loop;i++) {
System.out.println(this.getName()+" - "+testId.get());
try {this.sleep(1000);} catch (InterruptedException e) {}
}
}
public static void main(String args[]) {
new MyThreadLocal("hello-0").start();
try {Thread.sleep(1000);} catch (InterruptedException e) {}
new MyThreadLocal("hello-1").start();
}
}
output is
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0
Thread-0 - null
Thread-1 - hello-0