}
This example creates a single MyRunnable
instance which is passed to two different threads. Both threads execute the run()
method, and thus sets different values on the ThreadLocal
instance. If the access to the set()
call had been synchronized, and it had not been a ThreadLocal
object, the second thread would have overridden the value set by the first thread.
However, since it is a ThreadLocal
object then the two threads cannot see each other's values. Thus, they set and get different values.
InheritableThreadLocal
The InheritableThreadLocal
class is a subclass of ThreadLocal
. Instead of each thread having its own value inside a ThreadLocal
, the InheritableThreadLocal
grants access to values to a thread and all child threads created by that thread.