Each instance of the ThreadLocal class describes a thread-local variable.
A thread-local variable acts as a multi-slot variable. Each thread can store a different value in the same variable. Each thread sees only its value and is unaware of other threads having their own values in this variable.
The following code demos how to use ThreadLocal to associate a different user ID with each of two threads. Values stored in thread-local variables are not related. When a new thread is created, it gets a new storage slot containing initialValue()'s value.
public class Main {
private static volatile ThreadLocal userID = new ThreadLocal();
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
if (name.equals("A"))
userID.set("A");
else
userID.set("B");
System.out.println(name + " " + userID.get());
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}
InheritableThreadLocal is a subclass of ThreadLocal. The following code shows how to use InheritableThreadLocal to pass a parent thread's Integer object to a child thread.
public class Main {
private static volatile InheritableThreadLocal intVal = new InheritableThreadLocal();
public static void main(String[] args) {
Runnable rP = new Runnable() {
@Override
public void run() {
intVal.set(new Integer(10));
Runnable rC = new Runnable() {
public void run() {
Thread thd;
thd = Thread.currentThread();
String name = thd.getName();
System.out.println(name + " " + intVal.get());
}
};
Thread thdChild = new Thread(rC);
thdChild.setName("A");
thdChild.start();
}
};
new Thread(rP).start();
}
}