print numbers using two threads in java

Print Numbers Using Two Threads in Java – Concurrent Coding Example

By Hannah Martin
AD

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.

AD
80+ Pattern Programs In Java
80+ Pattern Programs In Java
Java - Add two binary numbers
Java - Add two binary numbers
Prime Number & Flowchart Notes for Beginners
Prime Number & Flowchart Notes for Beginners

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.

two different types of numbers that appear to be written in the form of an array
two different types of numbers that appear to be written in the form of an array
Insertion Sort Algorithm in Java with Example
Insertion Sort Algorithm in Java with Example
a poster with different types of writing and numbers on it, including the words'jwa beginner notes '
a poster with different types of writing and numbers on it, including the words'jwa beginner notes '
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.

AD
an image of a computer screen with text
an image of a computer screen with text
How to Reverse Numbers in Java, C, C#?
How to Reverse Numbers in Java, C, C#?
How to swap two Integers without using a temporary variable in Java? [Solution]
How to swap two Integers without using a temporary variable in Java? [Solution]
GENERICS IN JAVA
GENERICS IN JAVA
One Technique That Solves 100+ DSA Problems
One Technique That Solves 100+ DSA Problems
a blackboard with the words swap two numbers using temp variable to write them
a blackboard with the words swap two numbers using temp variable to write them
a white board with numbers on it and an arrow pointing up to the left side
a white board with numbers on it and an arrow pointing up to the left side
Error Correction and Detection Codes
Error Correction and Detection Codes
QuickSort Algorithm Example in Java using Recursion - Tutorial
QuickSort Algorithm Example in Java using Recursion - Tutorial
a screen shot of some type of programming program with numbers and symbols in the background
a screen shot of some type of programming program with numbers and symbols in the background
JAVA Tutorial : Thread , Multi Thread Example
JAVA Tutorial : Thread , Multi Thread Example
Arrays unidimensionales en Java
Arrays unidimensionales en Java
Java Bootcamp London & UK – Part Time Java Developer Program
Java Bootcamp London & UK – Part Time Java Developer Program
JavaScript Data type
JavaScript Data type
Javascript Cheet cheet
Javascript Cheet cheet
PATTERN
PATTERN
[Solved] How to count Vowels and Consonants in Java String Word? Example
[Solved] How to count Vowels and Consonants in Java String Word? Example
Java script string method
Java script string method
Post order traversal Algorithms for Binary Tree in Java with example
Post order traversal Algorithms for Binary Tree in Java with example
How to #swap two numbers without using a third variable in C. || #sahilgupta || #thenepalidev ||
How to #swap two numbers without using a third variable in C. || #sahilgupta || #thenepalidev ||
AD