There is a problem in the following code
PackageCn.itcast.heima2;ImportJava.util.HashMap;ImportJava.util.Random; Public classThreadscopesharedata {Private Static intdata = 0; Private StaticHashmap<thread, integer> threaddata =NewHashmap<>(); Public Static voidMain (string[] args) { for(inti = 0; I < 2; i++) { NewThread (NewRunnable () {@Override Public voidrun () {//TODO auto-generated Method Stubdata =NewRandom (System.currenttimemillis ()). Nextint (); System.out.println (Thread.CurrentThread (). GetName ()+ "has put data:" +data); Threaddata.put (Thread.CurrentThread (), data); NewA (). get (); NewB (). get (); }}). Start (); } } Static classA { Public voidget () {intData=Threaddata.get (Thread.CurrentThread ()); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "have put data:" +data); } } Static classB { Public voidget () {intData=Threaddata.get (Thread.CurrentThread ()); System.out.println ("B from" + Thread.CurrentThread (). GetName () + "have put data:" +data); } }}
Workaround:
PackageCn.itcast.heima2;ImportJava.util.HashMap;ImportJava.util.Random; Public classThreadscopesharedata {Private Static intdata = 0; Static Long[] seed =New Long[] {12345612, 654321 }; Private StaticHashmap<thread, integer> threaddata =NewHashmap<>(); Public Static voidMain (string[] args) {NewThread (Newthreadscopesharedata.myrunnable () {@Override Public voidrun () {//TODO auto-generated Method Stubdata =MyRunnable.rd.nextInt (); System.out.println (Thread.CurrentThread (). GetName ()+ "has put data:" +data); Threaddata.put (Thread.CurrentThread (), data); NewA (). get (); NewB (). get (); }}). Start (); NewThread (Newthreadscopesharedata.myrunnable () {@Override Public voidrun () {//TODO auto-generated Method Stubdata =MyRunnable.rd.nextInt (); System.out.println (Thread.CurrentThread (). GetName ()+ "has put data:" +data); Threaddata.put (Thread.CurrentThread (), data); NewA (). get (); NewB (). get (); }}). Start (); } Static classA { Public voidget () {intData=Threaddata.get (Thread.CurrentThread ()); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "have put data:" +data); } } Static classB { Public voidget () {intData=Threaddata.get (Thread.CurrentThread ()); System.out.println ("B from" + Thread.CurrentThread (). GetName () + "have put data:" +data); } } Abstract Static classMyrunnableImplementsRunnable {StaticRandom rd =NewRandom (); Public Abstract voidrun (); }}
(Dark Horse Java multi-threading and concurrent Library advanced application) 05 The concept and function of shared variables in thread scope