Shared data within the Java thread range
Shared data within the thread range, which is commonly used in JavaEE, and less in Android
A thread calls three modules A, B, and C. The expressions or variables in the module call to access A data. The data can be static.
Another thread also calls three modules A, B, and C. The expressions or variables in the module access the data, not the data just now, but the other
In the same code, one thread has one point of data.
import java.util.HashMap;import java.util.Map;import java.util.Random;public class ThreadScopeShareData {private static int data = 0;private static Map
threadData = new HashMap
();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);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);}}}
Application Scenario: database, one method is input data, one method is output data, two independent objects,
A is inputting data into B, B is outputting data out, A-> B->
C is inputting data into D, D is outputting data out, C-> D->
The two lines share the same link object. If the line C ends and the result is submitted, will the thread where A is located be interrupted, therefore, each thread operates on its own data.
The operated data is the data within the scope of the thread, and is irrelevant to the data on the other thread (the same is true for bank transfers)
The preceding example demonstrates that data is shared within the thread range (different modules), out of the thread range, and data is independent.