2

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();
    }
}
shu
  • 115
  • 1
  • 9
  • 3
    `thread.run();` change this to `thread.start()` – MartinS Feb 16 '16 at 16:18
  • Other duplicates (if someone wish to change current one since it may be too general): http://stackoverflow.com/q/8258536 http://stackoverflow.com/q/20323697 – Pshemo Feb 16 '16 at 16:28

1 Answers1

6

Because there are no threads in your program and luckily sequential programs don't have race issues. You calling thread.run which calls the run method and doesn't start any threads. Use thread.start to launch a thread instead.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77