Java line: Singleton hidden threadlocal for thread data sharing

Source: Internet
Author: User

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

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.