After executing incrementing thread, variable is always the same

pipilam :

Im trying to understand threads. I wrote simple program.

public class Main {
    static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter++;
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter++;
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter);
    }
}

The result is always 2000, but I do not know understand why. Any of the run methods are not synchronized so why it is giving me always the same result.

If I write:

 t1.start();
        t1.join();
        System.out.println(counter);
        t2.start();
        System.out.println(counter);

then I got result: 1000,1000. Why it is always equals to 1000?

WJS :

You're loops are so short that t1 finishes before t2 gets going. Try 100,000 instead. Lack of synchronization does not guarantee you will have concurrency issues but correctly incorporating synchronization will prevent them.

Guess you like

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