Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After executing incrementing thread, variable is always the same

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?

like image 951
pipilam Avatar asked Apr 16 '26 03:04

pipilam


1 Answers

Your 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.

like image 192
WJS Avatar answered Apr 18 '26 15:04

WJS