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