LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 1

Print odd and even numbers with two threads in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Use two threads – one printing odd numbers and one printing even numbers – coordinated with wait/notify so that 1 to 10 come out in order.

Solution
Main.java
public class Main {
    private int next = 1;
    private final int max = 10;
    private final StringBuilder out = new StringBuilder();

    synchronized void print(boolean odd) throws InterruptedException {
        while (next <= max) {
            while (next <= max && (next % 2 == 1) != odd) wait();
            if (next > max) break;
            out.append(next).append(odd ? "(O) " : "(E) ");
            next++;
            notifyAll();
        }
        notifyAll();                                // let the other thread see that we are done
    }

    public static void main(String[] args) throws InterruptedException {
        Main m = new Main();
        Thread even = new Thread(() -> { try { m.print(false); } catch (InterruptedException e) { } });
        Thread odd = new Thread(() -> { try { m.print(true); } catch (InterruptedException e) { } });
        even.start(); odd.start();
        even.join(); odd.join();
        System.out.println(m.out.toString().trim());
    }
}

Output Verified by compiling and running

1(O) 2(E) 3(O) 4(E) 5(O) 6(E) 7(O) 8(E) 9(O) 10(E)

Each thread waits until it is its turn (odd or even); the shared counter and notifyAll enforce strict alternation.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links