Global sum wrong with multi threads in JAVA -


i'm new multi-threads in java , made little code see how works. have global = 0 global int variable, , for loop initialize lot of threads (100) add 1 global variable.
@ end of code result should 100, not. have 99 @ end of code or other number (around 100). question is, why threads "fight" between them , don't make sum right?

public class test extends thread {     public static int global =0;     public static void main(string[] args) throws exception {                 for(int i=0;i<100;i++){                 string stream = string.valueof(i);                 new test2(stream).start();                 }                 thread.sleep(1000);                 system.out.println(global);     }     public test(string str) {         super(str);     }     public void run() {         int = integer.parseint(getname());         global = global+1;         system.out.println("el hilo "+a+" tiene el nĂºmero "+global);     } } 

i know don't need int = integer.parseint(getname());, pretend yo use name in future. and, if delete result wrong anyway.

this classic race condition.

one of threads, call "a", has read value global, 10, , added 1 it, hasn't stored value 11 global.

another of threads, call "b", reading "old" value of global, 10, it's adding 1 it, , stores value 11 global.

then thread "a" allowed store value 11 global. 2 increments have taken place, net result 1 increment has taken place.

this occurs because operation of incrementing value , storing variable not atomic. means there multiple separate operations if interrupted, yield incorrect result.

you must create synchronized block enforce operation being atomic. can lock on class object itself.

synchronized (test.class) {     global = global+1; } 

as alternative, may make global variable atomicinteger, handles atomic updates you.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -