Why is this multithreaded counter producing the right result?

toy :

I'm learning multithreaded counter and I'm wondering why no matter how many times I ran the code it produces the right result.

public class MainClass {
    public static void main(String[] args) {
        Counter counter = new Counter();
        for (int i = 0; i < 3; i++) {
            CounterThread thread = new CounterThread(counter);
            thread.start();
        }
    }
}

public class CounterThread extends Thread {
    private Counter counter;
    public CounterThread(Counter counter) {
        this.counter = counter;
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            this.counter.add();
        }
        this.counter.print();
    }
}

public class Counter {
    private int count = 0;
    public void add() {
        this.count = this.count + 1;
    }
    public void print() {
        System.out.println(this.count);
    }
}

And this is the result

10
20
30

Not sure if this is just a fluke or is this expected? I thought the result is going to be

10
10
10
manouti :

Try increasing the loop count from 10 to 10000 and you'll likely see some differences in the output.

The most logical explanation is that with only 10 additions, a thread is too fast to finish before the next thread gets started and adds on top of the previous result.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93420&siteId=1