Sunday, April 6, 2025

AlternatingPrinter ( wait() & notify() )




class AlternatingPrinter {
   private final Object lock = new Object();
// Indicates whether it's the number thread's turn
 private volatile boolean numberTurn = true;

public static void main(String[] args) {
AlternatingPrinter printer = new AlternatingPrinter();
Thread numberThread = new Thread(() -> printer.printNumbers());
Thread letterThread = new Thread(() -> printer.printLetters());
numberThread.start();
letterThread.start();
}
public void printNumbers() {
for (int i = 1; i <= 26; i++) { // Adjust the range as needed
synchronized (lock) {
while (!numberTurn) {
try {
lock.wait(); // Wait until it's this thread's turn
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print(i + " ");
numberTurn = false; // Pass the turn to the letter thread
lock.notifyAll(); // Notify the waiting thread
}
}
}
public void printLetters() {
for (char c = 'A'; c <= 'Z'; c++) { // Adjust the range as needed
synchronized (lock) {
while (numberTurn) {
try {
lock.wait(); // Wait until it's this thread's turn
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print(c + " ");
numberTurn = true; // Pass the turn to the number thread
lock.notifyAll(); // Notify the waiting thread
}
}
}

} 

No comments:

Post a Comment

CompletableFuture

  Welcome back to  our concurrency series ! In our first discussion, we likely touched on the traditional models of threading. Today, we’re ...