Print Numbers Using Two Threads in Java – Concurrent Coding Example
Printing numbers using two threads in Java is a classic concurrency problem that demonstrates the coordination between multiple threads executing within a single process. This exercise moves beyond simple loop structures, highlighting the need for precise thread management and communication. The primary challenge lies in ensuring that the threads alternate their execution in a predictable and correct sequence, preventing race conditions that could lead to jumbled output or inconsistent states.
At its core, this task requires implementing a mechanism where one thread is responsible for printing even numbers while the other handles odd numbers. The threads must operate in a strict alternation, printing 1, 2, 3, 4, and so on, in a synchronized manner. Achieving this relies heavily on Java's concurrency utilities, specifically the wait() and notify() methods, which allow threads to pause execution until a specific condition is met, thereby ensuring orderly access to shared resources.
Understanding the Synchronization Challenge
Without proper synchronization, the two threads will compete for the CPU, resulting in unpredictable output. For instance, the even thread might print its number before the odd thread has printed its preceding number, breaking the sequential flow. The core of the solution involves a shared object that acts as a lock and a state variable that indicates which thread's turn it is to print. This shared state must be accessed and modified atomically to prevent inconsistencies.
Leveraging wait() and notify()
The wait() method causes the current thread to release the lock and enter a waiting state until another thread invokes notify() on the same object. In the two-thread printing scenario, after a thread prints its number, it calls notify() to wake up the waiting thread and then calls wait() to give up the lock and pause. The awakened thread checks the state, prints its number, and then repeats the cycle. This handshake mechanism is crucial for maintaining the correct order.
Implementation with a Turn-Based Logic
A common and effective approach involves a turn-based flag that dictates which thread should proceed. The shared resource includes a boolean flag, such as isOddTurn, initialized to true to allow the odd thread to run first. Each thread enters a synchronized block on the shared object, checks the flag in a loop, and proceeds only when the flag matches its designated turn. After printing, the thread flips the flag and notifies the waiting thread.
| Thread | Condition Check | Action | State Update |
|---|---|---|---|
| Odd Thread | !isOddTurn
| Prints the current number | isOddTurn = true
|
| Even Thread | isOddTurn
| Prints the current number | isOddTurn = false
|
Modern Approaches with java.util.concurrent
While wait() and notify() provide fundamental control, the java.util.concurrent package offers more robust and flexible tools. The Lock and Condition API, for example, allow for more granular control over thread signaling, enabling the creation of multiple condition queues. Furthermore, high-level constructs like Semaphore or CyclicBarrier can be adapted to manage thread execution flow, though they might be more complex than necessary for this specific alternating print task.
Ultimately, mastering the synchronization of two threads to print numbers is a foundational skill for any Java developer. It solidifies the understanding of thread lifecycles, monitor locks, and the critical importance of atomic operations. By implementing and analyzing these patterns, developers gain the insight needed to tackle more complex concurrent programming challenges, ensuring their applications remain performant and reliable under heavy load.