Threadlocal shared variables within a thread scope

Source: Internet
Author: User

emulate the Threadlocal class implementation : Thread-scoped shared variables, each thread can only access his own, and cannot access other threads.

 PackageCom.ljq.test.thread;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Random;/*** thread-wide Shared variables * * Three modules shared data, main thread module and AB module *@authorAdministrator **/ Public classThreadscopesharedata {//prepare the shared data    Private Static intdata = 0; //store data for each thread    Private StaticMap<thread, integer> threaddata =NewHashmap<thread, integer>();  Public Static voidMain (string[] args) {//Start Two threads         for(inti = 0; I < 2; i++) {            NewThread (NewRunnable () {@Override Public voidrun () {//now modify the data in the current thread, give the modification information                    intdata =NewRandom (). Nextint (); //Store The thread information and the corresponding data.Threaddata.put (Thread.CurrentThread (), data); System.out.println (Thread.CurrentThread (). GetName ()+ "has put data:" +data); NewA (). get (); NewB (). get ();        }}). Start (); }    }    Static classA { Public voidget () {intdata =Threaddata.get (Thread.CurrentThread ()); System.out.println ("A from" +Thread.CurrentThread (). GetName ()+ "Get data:" +data); }    }    Static classB { Public voidget () {intdata =Threaddata.get (Thread.CurrentThread ()); System.out.println ("B from" +Thread.CurrentThread (). GetName ()+ "Get data:" +data); }    }}

Operation Result:


Xxx
Xxx
xxxxxxx
Xxx
Xxx
Xxx

Threadlocal shared variables within a thread scope

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.