How to Print Odd and Even Numbers Using Threads in Java?

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

Related Questions

⦿How to Check if an IP Address is Reachable in Java?

Learn how to determine if an IP address is alive in Java with our stepbystep guide and code examples.

⦿How to Enable a Custom JavaFX Component to Fill All Available Space in Its Parent Layout

Learn how to make your JavaFX custom component utilize all available space from its parent layout effectively.

⦿How to Trigger a Hudson Build with HTTP POST Including File Upload and Parameters

Learn how to initiate a Hudson build using HTTP POST requests with file uploads and parameters for seamless CI automation.

⦿How to Display the Name of an Android Bluetooth Device

Learn how to display the names of Bluetooth devices in Android apps with our expert guide including coding examples and common mistakes.

⦿How to Use EGit with a Self-Signed HTTPS Certificate

Learn how to configure EGit to work with selfsigned HTTPS certificates in your Git repositories.

⦿How to Retrieve Only the Class Name at Runtime in JavaScript?

Learn how to obtain just the class name at runtime in JavaScript with clear examples and explanations.

⦿How to Check if an Enum Contains a Constant by Name in Java?

Learn how to determine if a given name exists in a Java Enum using reflection and best practices for efficient coding.

⦿How Does Method Overloading Work in Objective-C?

Learn about method overloading in ObjectiveC its capabilities examples and common mistakes to avoid.

⦿How to Move Beyond the Factory Pattern in Python Using Advanced Techniques?

Explore advanced techniques to go beyond the factory design pattern in Python including dependency injection and builder patterns.

⦿How to Set a JLabel Background to Transparent in Java Swing?

Learn how to make a JLabel background transparent in Java Swing with expert tips and code samples.

© Copyright 2025 - CodingTechRoom.com