I have read many articles on why ThreadLocal
variable need to be static(although not necessary), but I didn't get the idea why it should be static.
I have read it here and many other links but didn't get the idea.
I have done something like this
public class ThreadLocalDemo{
public static void main(String[]args)throws Exception{
SharedRersource r1= new SharedRersource();
Thread t1= new Thread(r1);
Thread t2= new Thread(r1);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main thread Exiting...");
}
}
class SharedRersource implements Runnable{
private ThreadLocal<Integer> threadId = new ThreadLocal(){
protected Integer initialValue(){
return (int)(Math.random()*100);
}
};
public void run(){
try{
Thread.sleep(2000);
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(threadId.get());
}
};
Here thread t1 and t2 is having private copy of threadId than why It should be static
Please give a better understanding to me. Thanks