I'm new to multi-threads in Java and I made a little code to see how it works. I have global = 0
as a global int variable, and with a for
loop I initialize a lot of threads (100) to add 1 to my global variable.
At the end of the code the result should be 100, but is not. I have sometimes 99 at the end of the code or any other number (around 100). So my question is, why the threads "fight" between them and don't make the 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 a = Integer.parseInt(getName());
global = global+1;
System.out.println("El hilo "+a+" tiene el número "+global);
}
}
I know that I don't need int a = Integer.parseInt(getName());
, but I pretend yo use the name in the future. And, if I delete that now the result is wrong anyway.