Concepts and functions of shared variables within the thread range

Source: Internet
Author: User
import java.util.HashMap;import java.util.Map;import java.util.Random;public class ThreadScopeShareData {private static int data = 0;private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();  public static void main(String[] args) {for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {int data = new Random().nextInt();System.out.println(Thread.currentThread().getName()+ " has put data :" + data);threadData.put(Thread.currentThread(), data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data);}}}

The thread shares the variable data, sets the data as a static variable, places it in the map when the thread is assigned a random value, and obtains it when the new A or B class is used.

When assigning values to data, you need to redefine the new memory block. If an int variable is not added, the output values are exactly the same.

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.