The 30 second answer
Ordering is not guaranteed, so the output can interleave in any order. If they also share a counter without synchronization you get a data race: lost updates, duplicates or skips, and visibility bugs under the Java Memory Model. I fix it with a shared lock and wait/notify on a turn condition, two Conditions on a ReentrantLock, Semaphores that hand off, or an AtomicInteger turn check for a demo.
Ordering is not guaranteed: output interleaves arbitrarily (e.g. 1,3,5,2,…). If they share a counter without synchronization you also get a data race — lost updates, duplicates/skips, and visibility problems (a thread may not see the other's write; the JMM gives no happens-before). Fix: shared lock + wait/notifyAll on a turn condition, ReentrantLock with two Conditions, two Semaphores handing off, or an AtomicInteger with turn check (busy-wait; fine for demo only).
Runnable fix with two semaphores that hand the turn back and forth:
import java.util.concurrent.Semaphore;
public class OddEven {
public static void main(String[] args) throws InterruptedException {
Semaphore oddTurn = new Semaphore(1); // odd goes first
Semaphore evenTurn = new Semaphore(0);
Thread odd = new Thread(() -> {
for (int i = 1; i <= 100; i += 2) {
oddTurn.acquireUninterruptibly();
System.out.println(i);
evenTurn.release(); // hand the turn over
}
});
Thread even = new Thread(() -> {
for (int i = 2; i <= 100; i += 2) {
evenTurn.acquireUninterruptibly();
System.out.println(i);
oddTurn.release();
}
});
odd.start(); even.start();
odd.join(); even.join();
}
}
Sources (2)
- JLS §17.4 Memory Modeldocs.oracle.com
- Semaphoredocs.oracle.com