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());
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!