Thread-wide shared data, more commonly used in Java EE, less Android
A thread calls A,b,c three modules, and the expression or variable call in the module accesses a data that can be static
Another thread also calls A,b,c three modules, and the data accessed by the expression or variable in the module is not just the data, but another
The same code, a piece of data on a thread
[Java]View Plaincopy
- 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 () {
- 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: A database, one method is to input data, one method is output data, two independent objects,
A in the input data to B, b in the outward output of the data,a->b->
C in the input data to D, d in the outward output of the data,c->d->
The two lines share the same linked object, if the C line is finished, and the result is submitted, then the thread where a is located is interrupted, so each thread is working on its own data, the thread
The data of the operation, which is the data within the scope of its own thread, regardless of the data on the other thread (bank transfer is the same)
The above examples demonstrate that the thread scope, (different modules) data sharing, the thread range outside, the data independent
Shared data in the Java thread scope