In the previous "Android Multithreading Research (5)--Thread sharing data" in the data sharing between threads to learn and research, this article we look at how to solve the problem of data isolation between multiple threads, what is data isolation? For example, we now have two threads open, each of these two threads will be assigned to the same global variable data, each thread to manipulate the variables after it is assigned, this need to use isolation. First look at a piece of code:
Import Java.util.Random;
public class Threadlocaltest {private static int data = 0;
public static void Main (string[] args) {for (int i=0; i<2; i++) {new Thread (new Runnable () { @Override public void Run () {data = new Rand
Om (). Nextint ();
System.out.println (Thread.CurrentThread (). GetName () + "has put data:" + data);
New A (). get ();
New B (). get ();
}). Start (); } static class a{public int get () {System.out.println ("A from" + Thread
. CurrentThread (). GetName () + "has get data:" + data);
return data; } static class b{public int get () {System.out.println (' B from ' + Thread . curRentthread (). GetName () + "has get data:" + data);
return data; }
}
}
Run Result:
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
From the above we can see that both Thread-0 and Thread-1 are operating variable data, but two threads do not have a separation between the operations of the operation, so the two threads in the output share a data variable.
We will revise the above code as follows:
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Random;
public class Threadlocaltest {//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 () { @Override public void Run () {//data = new Ra
Ndom (). Nextint ();
int data = new Random (). Nextint ();
Map.put (Thread.CurrentThread (), data);
System.out.println (Thread.CurrentThread (). GetName () + "has put data:" + data);
New A (). get ();
New B (). get ();
}). Start (); } static class a{public int get () {SYSTEM.OUT.PRintln ("A from" + Thread.CurrentThread (), getName () + "has get data:" + map.get (Thread.currentthre
AD ()));
Return Map.get (Thread.CurrentThread ()); } static class b{public int get () {System.out.println (' B from ' + Thread
. CurrentThread (). GetName () + "has get data:" + Map.get (Thread.CurrentThread ());
Return Map.get (Thread.CurrentThread ()); }
}
}