Multithreading is easy "non-thread safe" situation, is because of the use of global variables, but not very good control of the situation. So whatever program you do, use global variables with caution
"Non-thread-safe" occurs when multiple threads are concurrently accessing instance variables in the same object, with the result of "dirty" reads.
The following code will show the "dirty" read:
Packagecom.ming.thread.t1; Public classCount {intCount=0; Public voidAdd (String str) {if("a". Equals (str)) {Count=100; Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (count); }Else{Count=200; System.out.println (count); } }}
Create Two threads:
Package com.ming.thread.t1; Public class extends thread{ Private count count; Public Threada (count count) { this. count=count; } Public void run () { Count.add ("a");} }
Package com.ming.thread.t1; Public class extends thread{ Private count count; Public threadb (count count) { this. count=count; } Public void run () { count.add ("B");} }
In establishing a test class:
Package com.ming.thread.t1; Public class Test { publicstaticvoid main (string[] args) { count count= New Count (); Threada a=new Threada (count); A.start (); THREADB b=new threadb (count); B.start (); }}
Last output: 200 200, apparently dirty read data has appeared.
Finally, the variable is saved in the method, which solves the problem.
So write the code to pay attention to this problem.
Java multi-threading, how to prevent dirty read data