Programming Assignment: Even and Odd Thread
Name: Harshitha Gorrepati
LID: L20624290
Date:2/26/2025
REPORT
Approach Taken:
The program implements a multi-threaded approach to print numbers from 1 to 100 in sequential
order, ensuring that odd and even numbers are printed alternately by separate threads.
1. SharedPrinter Class: This class acts as a shared resource between two threads. It contains
synchronized methods to print odd and even numbers while maintaining proper order.
2. OddThread and EvenThread Classes: These threads are responsible for printing odd and
even numbers respectively. Each thread calls the appropriate method in SharedPrinter to
print its numbers.
3. Synchronization Mechanism: The use of synchronized methods ensures that only one thread
executes at a time, preventing race conditions. The wait() and notify() methods are used for
thread coordination.
Synchronization Mechanism:
Synchronization is implemented using Java’s built-in synchronized keyword along with wait() and
notify() methods.
printOdd(int number): This method is synchronized to ensure only the odd thread can
access it when isOdd is true. If isOdd is false, the thread waits until notified by the even
thread.
printEven(int number): This method is also synchronized, allowing only the even thread to
access it when isOdd is false. If isOdd is true, the thread waits until notified by the odd
thread.
Thread Coordination:
o The odd thread starts first and prints an odd number, then sets isOdd = false and
notifies the even thread.
o The even thread prints the next even number, sets isOdd = true, and notifies the odd
thread.
o This alternation ensures that numbers are printed in the correct order without
conflicts.
Challenges Faced and Solutions:
1. Thread Synchronization Issues:
o Challenge: Without proper synchronization, both threads might access the shared
resource simultaneously, leading to incorrect output.
o Solution: The synchronized keyword was used to ensure that only one thread
executes its printing method at a time.
2. Deadlock Prevention:
o Challenge: If wait() and notify() were not used correctly, one thread might be left
waiting indefinitely.
o Solution: Proper use of wait() in a loop ensures that a thread only proceeds when it
is its turn, and notify() signals the next thread to continue execution.
3. Efficient Resource Utilization:
o Challenge: Continuous busy-waiting or polling could lead to CPU wastage.
o Solution: Using wait() ensures that a thread only wakes up when it receives a
notify(), making the program efficient.