I'm learning multi-threading and want to write some code with race condition. However these code does not work: I've run the code for many times, but it always print 10 which is the correct result without race condition. Could someone tell why? Thanks.
Here's the main function. It will create 10 threads to modify one static variable, and print this variable at the end.
public static void main(String[] args) {
int threadNum = 10;
Thread[] threads = new Thread[threadNum];
for (int i = 0; i < threadNum; i++) {
threads[i] = new Thread(new Foo());
}
for (Thread thread : threads) {
thread.run();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
// will always print 10
System.out.println(Foo.count);
}
And here's the definition of Foo:
class Foo implements Runnable {
static int count;
static Random rand = new Random();
void fn() {
int x = Foo.count;
try {
Thread.sleep(rand.nextInt(100));
} catch (InterruptedException e) {
}
Foo.count = x + 1;
}
@Override
public void run() {
fn();
}
}