Trying this piece of code, I found out that no matter how many times I run the program or iterations are done, race conditions never occur. I know this is not thread safe and I can't understand the reason why this behavior is happening. Any documentation/ideas are welcomed.
Main.java
public class Main {
static final int N = 1000;
static int ITERATIONS = 1000000;
public static void main(String[] args) {
Thread threads[] = new Thread[10];
boolean found = true;
for (int j = 0; j < ITERATIONS; j++) {
MyThread.val = 0;
for (int i = 0; i < 10; i++)
threads[i] = new Thread(new MyThread());
for (int i = 0; i < 10; i++)
threads[i].run();
for (int i = 0; i < 10; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (MyThread.val != N * 10) {
System.out.println("different !");
found = false;
}
}
if (found)
System.out.println("The value is always correct.");
}
}
MyThread
public class MyThread implements Runnable {
static int val = 0;
@Override
public void run() {
for (int i = 0; i < Main.N; i++)
val = val + 1;
}
}
I tried to run the program for dozens of time, but it always prints "The value is always correct".
(This is not homework or whatever)