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.
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());
}
}
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.