Using threadlocal to generate unique identities and implementation principles for threads

Source: Internet
Author: User
Tags object object

1, in multithreaded programming, sometimes need to automatically generates each start line into a unique identity, this time, through a threadlocal variable to save the identity of each thread is the most effective, most convenient way.

2. ThreadLocal instances are typically private static fields in a class

3, in the construction of threadlocal, by overriding the subclass of the method to rewrite the sequence number. The purpose of generating the serial number for each thread is thus achieved.

Importjava.util.Collections;ImportJava.util.HashMap;ImportJava.util.Map;/*** A multithreaded object with a private variable serialnum that holds the ordinal number of the object thread *@authorYinchuan.chen **/classMultithreadobjectextendsThread {//Line program number variable    PrivateSerialnum Serialnum;  PublicMultithreadobject (Serialnum serialnum) {//Initialize line program number save variable         This. Serialnum =Serialnum; }     /*** A schematic multi-threaded business approach*/      Public voidrun () {System.out.println ("Thread" + thread.currentthread (). GetName () + "The serial number is" +serialnum.getnextnum ()); } }/*** A schematic threadlocal implementation that is equivalent to the Threadlocal API in the JDK *@authorYinchuan.chen **/classsimplethreadlocal {//a thread map to hold the thread and its corresponding variable copy    PrivateMap Threadmap = Collections.synchronizedmap (NewHashMap ());  Public voidset (Object object) {Threadmap.put (Thread.CurrentThread (), object); }      PublicObject Get () {Thread CurrentThread=Thread.CurrentThread (); Object obj=Threadmap.get (CurrentThread); if(obj = =NULL&&!Threadmap.containskey (CurrentThread)) {obj=InitialValue ();         Threadmap.put (CurrentThread, obj); }         returnobj; }      Public voidRemove () {Threadmap.remove (Thread.CurrentThread ()); }     protectedObject InitialValue () {return NULL; } }/*** Line Program number identification generation tool *@authorYinchuan.chen **/classSerialnum {//class-level thread number variable, pointing to the ordinal of the next thread    Private StaticInteger nextnum = 0; //defines a threadlocal variable that holds an integer type of line program number//private static threadlocal<integer> Threadno = new threadlocal<integer> () {    Private StaticSimplethreadlocal Threadno =Newsimplethreadlocal () {//subclasses of threadlocal are defined by anonymous inner classes, overriding the InitialValue () method         Public synchronizedInteger InitialValue () {returnnextnum++;     }     }; /*** Get Line program number * *@returnLine Program number*/      Public intGetnextnum () {return(Integer) threadno.get (); } } Public classtesttreadlocal { Public Static voidMain (string[] args) {serialnum serialnum=NewSerialnum (); Multithreadobject M1=NewMultithreadobject (Serialnum); Multithreadobject m2=NewMultithreadobject (Serialnum); Multithreadobject M3=NewMultithreadobject (Serialnum); Multithreadobject M4=NewMultithreadobject (Serialnum);         M1.start ();         M2.start ();         M3.start ();         M4.start (); //The following test method is in the main thread, where the current threads areTestmainthread (); }      Public Static voidTestmainthread () {serialnum serialnum=NewSerialnum (); System.out.println ("Serial number of the main thread is" +serialnum.getnextnum ()); Serialnum serialNum2=NewSerialnum (); System.out.println ("Serial number of the main thread is" +serialnum2.getnextnum ()); } }

Using threadlocal to generate unique identities and implementation principles for threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.