Share:
A and B need to share the same thread, and a group of identical A and B shares also have a set of threads, and the two groups are not affected by each other.
Code:
Package Cn.itcast.lesson6;import Java.util.random;public class Threadlocaltest {public static void main (string[] args) { for (int i=0;i<2;i++) {new Thread (new Runnable () {public void run () {int data = new Random (). Nextint (); System.out.println (Thread.CurrentThread (). GetName () + "has put data:" + data); Mythreadscopedata.getthreadinstance (). SetName ("name" + data); Mythreadscopedata.getthreadinstance (). setage (data); new A (). get (); new B (). get ();}}). Start ();}} Static class A{public void Get () {Mythreadscopedata myData = mythreadscopedata.getthreadinstance (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "Getmydata:" + mydata.getname () + "," + mydata.getage ()) ;}} Static class B{public void Get () {Mythreadscopedata myData = mythreadscopedata.getthreadinstance (); System.out.println ("B from" + Thread.CurrentThread (). GetName () + "Getmydata:" +mydata.getname () + "," + mydata.getage ()) ;}}} Class Mythreadscopedata{private Mythreadscopedata () {}//single-case hidden threadlocal implementing data sharing public static/*synchronized*/mythreadscopedata getthreadinstance () {Mythreadscopedata instance = Map.get (); if (instance = = null) {instance = new Mythreadscopedata (); Map.set (instance);} return instance;} private static threadlocal<mythreadscopedata> map = new threadlocal<mythreadscopedata> ();p rivate String name;private int age;public String getName () {return name;} public void SetName (String name) {this.name = name;} public void Setage (int.) {this.age = age;} public int getage () {return age;}}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Java line: Singleton hidden threadlocal for thread data sharing