Java Reference
In-Depth Information
Whenyourunthisapplication,youwillobservethefollowingoutput(possiblynotin
this order):
A foxtrot
B charlie
Valuesstoredinthread-localvariablesarenotrelated.Whenanewthreadiscreated,
it gets a new storage slot containing
initialValue()
's value. Perhaps you would
prefer to pass a value from a parent thread, a thread that creates another thread,
to a
child thread
, the created thread. You accomplish this task with
Inherit-
ableThreadLocal
.
InheritableThreadLocal
isasubclassof
ThreadLocal
.Aswellasdeclar-
ingan
InheritableThreadLocal()
constructor,thisclassdeclaresthefollowing
protected
method:
•
T childValue(T parentValue)
calculatesthechild'sinitialvalueasa
functionoftheparent'svalueatthetimethechildthreadiscreated.Thismethod
is called from the parent thread before the child thread is started. The method
returnstheargumentpassedto
parentValue
andshouldbeoverriddenwhen
another value is desired.
thread's
Integer
object to a child thread.
Listing 4-30.
Different user IDs for different threads
class InheritableThreadLocalDemo
{
private static volatile InheritableThreadLocal<Integer>
intVal =
new InheritableThreadLocal<Integer>();
public static void main(String[] args)
{
Runnable rP = new Runnable()
{
@Override
public void run()
{
intVal.set(new Integer(10));
Runnable rC = new Runnable()
{