I just wanted to write an example for an race condition:
MyParallelClass.java:
public class MyParallelClass implements java.lang.Runnable {
public int counter = 0;
@Override
public void run() {
if (test.globalVar > 0) {
for (int i = 0; i < 1000000; i++) {
counter++;
}
test.globalVar--;
}
}
}
test.java:
public class test {
public static int globalVar;
public static void main(String[] args) {
globalVar = 1;
MyParallelClass a = new MyParallelClass();
MyParallelClass b = new MyParallelClass();
new Thread(a).start(); // Thread A
new Thread(b).start(); // Thread B
System.out.println(globalVar);
}
}
What I thought would happen:
I thought this could output either 0
if thread A was executed completely before Thread B starts.
The variable test.globalVar
could also get manipulated like this:
Thread A - Thread B
checks if (globalVar > 0)
looping ... checks if (globalVar > 0)
looping ... execute all four bytecode commands of "test.globalVar--;"
execute test.globalVar--;
so the value of test.globalVar
would be -1
.
So either one of the if-statements get executed or both.
What actually happened:
I got 0
and 1
as output of the main method. Why do I get 0
and 1
and not 0
and -1
?