Java Reference
In-Depth Information
Listing 4-29.
Different user IDs for different threads
class ThreadLocalDemo
{
private static volatile ThreadLocal<String> userID =
new ThreadLocal<String>();
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("foxtrot");
else
userID.set("charlie");
System.out.println(name+" "+user-
ID.get());
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}
After instantiating
ThreadLocal
and assigning the reference to a
volatile
classfieldnamed
userID
(thefieldis
volatile
becauseitisaccessedbydifferent
threads,whichmightexecuteonamultiprocessor/multicoremachine),thedefaultmain
thread creates two more threads that store different
String
objects in
userID
and
output their objects.