2021-03-29

Multithreading using synchronized

I am learning multithreading. I have a following code:

public class Intro {
    public static void main(String[] args) {
        new Intro().doCounter();
    }

    private int counter = 0;

    synchronized void increment() {
        counter++;
    }


    private void doCounter() {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1_000_000; i++) {
                    increment();
                }
                System.out.println("first: " + counter);
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1_000_000; i++) {
                    increment();
                }
                System.out.println("second: " + counter);
            }
        });

        thread1.start();
        thread2.start();


    }
}

Output (can differ):
first: 1741739
second: 2000000

The code has two threads. One thread increment the counter million times, while the second wait. Then the second increment it million times as well. I understand why the second thread get 2 million, but didn't get why the first thread get 1741739. Why it isn't 1 million for the first thread? I think it had to stop at 1 million. Thanks for explanation.



from Recent Questions - Stack Overflow https://ift.tt/3rEBxkR
https://ift.tt/eA8V8J

No comments:

Post a Comment