Thread join() does not wait
java, multithreading
Solution
The reason why you sometimes see `1` is not because `join()` fails to wait for the thread to finish, but because both threads tried to modify the value concurrently. When this happens, you may see unexpected results: for example, when both threads try to increment `count` which is zero, they both could read zero, then add 1 to it, and store the result. Both of them will store the same exact result, i.e. 1, so that's what you are going to see no matter how long you wait.
To fix this problem, add `synchronized` around the increment, or use `AtomicInteger`:
public static AtomicInteger count = new AtomicInteger(0);
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadAdd.class.getName()).log(Level.SEVERE, null, ex);
}
ThreadAdd.count.incrementAndGet();
}
Problem
I'm trying to learn about threads and I do not understand the `join()` method. I have a Thread (ThreadAdd.java) which adds 1 to a static int. ``` public class ThreadAdd extends Thread{ public static int count; @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(ThreadAdd.class.getName()).log(Level.SEVERE, null, ex); } ThreadAdd.count++; } } ``` In my `main` method I launch 2 threads : ``` public static void main(String[] args) throws InterruptedException { ThreadAdd s1 = new ThreadAdd(); ThreadAdd s2 = new ThreadAdd(); s1.start();s2.start(); s1.join(); s2.join(); System.out.println(ThreadAdd.count); } ``` I do not understand why most of the time the result is 2 but sometimes it returns 1.