I'm learning about synchronization and try to implement mutual exclusion, but even though I used join() method, main thread doesn't wait for two other to finish and counter ends with random number. The code:
public class Application {
static volatile int counter = 10000000;
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 5000000; i++) {
counter--;
}
};
long timeBefore = System.currentTimeMillis();
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
t1.join();
t2.join();
long timeAfter = System.currentTimeMillis();
long performance = timeAfter - timeBefore;
System.out.println("Application finished with counter : " + counter);
System.out.println("Application finished with time: " + performance + " ms");
}
}
Is my understanding of join() is incorrect and it doesn't make calling thread to wait for referenced one with the method?