Shared variables within the thread range

Source: Internet
Author: User

[Java]
Package cn. itcast. demo;
 
Import java. util. HashMap;
Import java. util. Map;
Import java. util. Random;
 
Public class ThreadScopeShareData {
/*
* Shared variables within the thread range
* Function: Shared variables within the thread scope refer to the write and read operations on the same variable at the same time by several threads,
* The data read by the same thread is the data written by itself.
*/
Private static int data = 0;
Private static Map <Thread, Integer> map = new HashMap <Thread, Integer> ();
Public static void main (String [] args ){
For (int I = 0; I <2; I ++ ){
New Thread (new Runnable (){

Public void run (){
Data = new Random (). nextInt ();
Map. put (Thread. currentThread (), data );
System. out. println (Thread. currentThread (). getName () + ": MAIN --->" + map. get (Thread. currentThread ()));
New A (). get ();
New B (). get ();
}
}). Start ();
}
}

Static class {
Public void get ()
{
System. out. println (Thread. currentThread (). getName () + "--->" + map. get (Thread. currentThread ()));
}
}
Static class B {
Public void get ()
{
System. out. println (Thread. currentThread (). getName () + "--->" + map. get (Thread. currentThread ()));
}
}

}

 

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.