multithreading - Java thread generate same value -
public class thinkthreadlocal { public static int data; public static void main(string[] args) { for(int = 0; < 2; i++) { new thread(new runnable(){ @override public void run() { data = new random().nextint(); system.out.println(thread.currentthread().getname() + " gene data:" + data); } }).start(); } } }
why prints same value?
thread-0 gene data:-751128970 thread-1 gene data:-751128970
it's because thread executed second setting value of data
before first thread printing anything. making minor modification code illustrates quite well:
public final class thinkthreadlocal { public static int data; public static void main(string[] args) { (int = 0; < 2; i++) { new thread(new runnable() { @override public void run() { int temp = data = new random().nextint(); system.out.println(thread.currentthread().getname() + " temp: " + temp); system.out.println(thread.currentthread().getname() + " shared: " + data); } }).start(); } } }
one execution of gave me:
thread-0 temp: 709919531 thread-1 temp: 2022218312 thread-0 shared: 2022218312 thread-1 shared: 2022218312
as can see, values being generated different (709919531 , 2022218312 in case), data
being overwritten second value before first value printed. shows unrelated seed of random
.
a second way show synchronize on class itself, (in case) block thread gets executed second until first has finished executing:
public final class thinkthreadlocal { public static int data; public static void main(string[] args) { (int = 0; < 2; i++) { new thread(new runnable() { @override public void run() { synchronized (thinkthreadlocal.class) { data = new random().nextint(); system.out.println(thread.currentthread().getname() + " shared: " + data); } } }).start(); } } }
which resulted in
thread-0 shared: 1811879710 thread-1 shared: 1738616729
Comments
Post a Comment