Member-only story
Sequential Execution of Two Threads Printing Numbers (1,2,3…) and Letters(A,B,C,..) in Java. So that it prints (1,A,2,B…)?
3 min readFeb 1, 2025
To ensure that two threads print in sequence — one printing numbers (1,2,3…) and the other printing letters (A,B,C…) — you can use synchronization mechanisms such as Locks and Condition Variables, Synchronized Blocks & Wait/Notify, or Atomic Variables & Busy-Waiting. Below is a solution using Lock
and Condition
from java.util.concurrent
, which ensures proper sequencing.
Solution1 :
package com.example.validation_demo.controller;
public class PrintTest {
private final Object lock = new Object();
private boolean numberTurn = true; // Indicates whether it's the number thread's turn
public static void main(String[] args) {
PrintTest printer = new PrintTest();
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) {…