Threadlocal
A local variable can be implemented in the thread and can be accessed anywhere in the thread. It can reduce the passing of the parameter package JP. co. realseed;
Public class threadlocaltest ...{
Private Static threadlocal tl_1 = new threadlocal ()...{
// Return the thread name, variable 1
Protected object initialvalue ()...{
Return "thread name 1:" + thread. currentthread (). getname ();
}
};
Private Static threadlocal tl_2 = new threadlocal ()...{
// Return the thread name, variable 2
Protected object initialvalue ()...{
Return "thread name 2:" + thread. currentthread (). getname ();
}
};
Public static void main (string [] ARGs )...{
For (INT I = 0; I <10; I ++ )...{
New thread (New runnable ()...{
Public void run ()...{
New threadlocaltest (). PRT ();
}
}). Start ();
}
}
// Print the thread name
Public void PRT ()...{
System. Out. println (tl_1.get ());
System. Out. println (tl_2.get ());
}
}
Inheritablethreadlocal
The instance can be shared between the child thread and the parent thread, or to reduce the passing of the parameter package JP. co. realseed;
Public class inheritablethreadlocaltest ...{
Private Static inheritablethreadlocal ITL = new inheritablethreadlocal ()...{
Protected object initialvalue ()...{
Return new stringbuffer ("hello ");
}
};
Public static void main (string [] ARGs )...{
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
New thread (New runnable ()...{
Public void run ()...{
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
New thread (New runnable ()...{
Public void run ()...{
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
(Stringbuffer) ITL. Get (). append (", wqf ");
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
}
}). Start ();
Try ...{
Thread. Sleep (1000 );
} Catch (interruptedexception ex )...{
Ex. printstacktrace ();
}
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
}). Start ();
Try ...{
Thread. Sleep (1000 );
} Catch (interruptedexception ex )...{
Ex. printstacktrace ();
}
System. Out. println (thread. currentthread (). getname () + ":" + ITL. Get ());
}
}