Import Java.util.Random;
public class Statictest {
private static int data = 0;
public static void Main (string[] args) {
//Open three threads for
(int i=0;i<3;i++) {
new Thread (new Runnable () {
@ Override public
Void Run () {
//each thread data value is the same, the program below has the explanation
data = new Random (). Nextint ();
System.out.println (Thread.CurrentThread (). GetName () + "has put data:" + data);
}
}). Start ();}}
Run Result:
Thread-1 has put data:367396051
Thread-2 has put data:367396051
Thread-0 has put data:367396051
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Random;
public class Threadscopesharedata {//static, which results in the same random value, a bit does not understand the private static int = 0;
With thread as key private static map<thread,integer> Threaddata = new Hashmap<thread, integer> (); public static void Main (string[] args) {//Open three threads for (int i=0;i<3;i++) {new Thread (new Runnable () {@Overri De public void Run () {//each thread data value is the same, because it is a static variable, change all, the final result is the same as the last thread data value//is overwritten by the later thread data value, because the static variable has only one copy//dat
A = new Random (). Nextint ();
So it's different. 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 map simulates threadlocal.
Run Result:
Thread-0 has put data:1500573848
Thread-2 has put data:1307429900
Thread-1 has put data:-1173968999
A from Thread-1 get data:-1173968999
A from Thread-0 get data:1500573848
A from Thread-2 get data:1307429900
B from Thread-1 get data:-1173968999
B from Thread-0 get data:1500573848
B from Thread-2 get data:1307429900