Question
What is the best way to print odd and even numbers using threads in Java?
public class OddEvenThread {
private static final int MAX_NUMBER = 20;
private static int number = 1;
public static void main(String[] args) {
Thread oddThread = new Thread(() -> {
while (number <= MAX_NUMBER) {
synchronized (OddEvenThread.class) {
while (number % 2 == 0) {
try {
OddEvenThread.class.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(number++);
OddEvenThread.class.notify();
}
}
});
Thread evenThread = new Thread(() -> {
while (number <= MAX_NUMBER) {
synchronized (OddEvenThread.class) {
while (number % 2 != 0) {
try {
OddEvenThread.class.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(number++);
OddEvenThread.class.notify();
}
}
});
oddThread.start();
evenThread.start();
}
}
Answer
Printing odd and even numbers using threads in Java involves coordinating two threads to ensure that they print the numbers in the correct sequence. This can be achieved using synchronization and wait/notify mechanisms.
public class OddEvenThread {
private static final int MAX_NUMBER = 20;
private static int number = 1;
public static void main(String[] args) { ... } // insert full code from above
Causes
- The need for concurrency and multi-threading in Java applications.
- The desire to demonstrate thread communication and synchronization effectively.
Solutions
- Implement synchronized blocks to ensure that only one thread accesses a critical section at a time.
- Use `wait()` to make a thread pause execution until another thread signals it to resume by calling `notify()`.
Common Mistakes
Mistake: Not using synchronization, leading to race conditions.
Solution: Always synchronize the block of code that checks and prints the numbers.
Mistake: Failing to manage thread interruptions properly.
Solution: Use try-catch blocks around wait statements to handle interruptions gracefully.
Helpers
- Java threading
- odd even numbers in Java
- synchronized threads
- Java multithreading examples