/*** Description: The concept and function of shared variables within a thread range. * @ Author: wnj. * @ Created: May 15, 2017. * @ Version: 1.0.*/ Public classThreadlocaltest {Private Staticthreadlocal<integer> x =NewThreadlocal<integer>(); Private StaticThreadlocal<mythreadscopedata> Mythreadscopedata =NewThreadlocal<mythreadscopedata>(); Public Static voidMain (string[] args) { for(inti=0;i<2;i++){ NewThread (NewRunnable () {@Override Public voidrun () {intdata =NewRandom (). Nextint (); System.out.println (Thread.CurrentThread (). GetName ()+ "has put data:" +data); X.set (data);/*mythreadscopedata myData = new Mythreadscopedata (); Mydata.setname ("name" + data); Mydata.setage (data); Mythreadscopedata.set (myData);*/mythreadscopedata.getthreadinstance (). SetName ("Name" +data); Mythreadscopedata.getthreadinstance (). setage (data); NewA (). get (); NewB (). get (); }}). Start (); } } Static classa{ Public voidget () {intdata =X.get (); System.out.println ("A from" +Thread.CurrentThread (). GetName ()+ "Get data:" +data);/*Mythreadscopedata myData = Mythreadscopedata.get (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "Getmydata:" + mydata.getname () + "," + mydata.getage ());*/ //get an instance related to this threadMythreadscopedata MyData =mythreadscopedata.getthreadinstance (); System.out.println ("A from" +Thread.CurrentThread (). GetName ()+ "Getmydata:" + mydata.getname () + "," +mydata.getage ()); } } Static classb{ Public voidget () {intdata =X.get (); System.out.println ("B from" +Thread.CurrentThread (). GetName ()+ "Get data:" +data); Mythreadscopedata MyData=mythreadscopedata.getthreadinstance (); System.out.println ("B from" +Thread.CurrentThread (). GetName ()+ "Getmydata:" + mydata.getname () + "," +mydata.getage ()); } }}classmythreadscopedata{PrivateMythreadscopedata () {} Public Static /*synchronized*/mythreadscopedata getthreadinstance () {//at this point the Map.get is the variable that gets itself, when multiple threads come in at the same time, get the variables of the thread itself, so this way does not need to add synchronizedMythreadscopedata instance =Map.get (); if(Instance = =NULL){//a thread in, Judge ==null, this time has not been assigned, just this time by the CPU dispatch to another thread, also Judge ==null//then it will be new two times .Instance =NewMythreadscopedata (); Map.set (instance); } returninstance; } //private static Mythreadscopedata instance = null;//new Mythreadscopedata (); Private Staticthreadlocal<mythreadscopedata> map =NewThreadlocal<mythreadscopedata>(); PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }}
Concept and function evolution of shared variables in thread-scoped mode