Untitled
unknown
java
2 years ago
1.6 kB
5
Indexable
public class OddEvenPrinter { private int count; private int maxCount; public OddEvenPrinter(int maxCount) { this.count = 1; this.maxCount = maxCount; } public synchronized void printOdd() { while (count <= maxCount) { if (count % 2 == 1) { System.out.println("Odd: " + count); count++; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } notify(); // Notify any waiting threads before finishing } public synchronized void printEven() { while (count <= maxCount) { if (count % 2 == 0) { System.out.println("Even: " + count); count++; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } notify(); // Notify any waiting threads before finishing } public static void main(String[] args) { final int MAX_COUNT = 10; OddEvenPrinter printer = new OddEvenPrinter(MAX_COUNT); Thread thread1 = new Thread(() -> { printer.printOdd(); }); Thread thread2 = new Thread(() -> { printer.printEven(); }); thread1.start(); thread2.start(); } }
Editor is loading...