Sobes.tech
Senior

class AlternatingPrinter { 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++) { System.out.print(i + " "); } } public void printLetters() { for (char c = 'A'; c <= 'Z'; c++) { System.out.print(c + " "); } } } Предположим, у вас есть два потока. Один из них выводит (1,2,3...), а другой — (A,B,C...). Как обеспечить их выполнение в чередующейся последовательности (1,A,2,B...)?

sobes.tech AI

Answer from AI

To ensure alternating output of streams (1, A, 2, B, ...), their operation must be synchronized, making each thread wait until the other outputs its element. In Java, this can be done using a monitor object and the wait()/notify() methods.

Example implementation:

public class AlternatingPrinter {
    private final Object lock = new Object();
    private 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++) {
            synchronized (lock) {
                while (!numberTurn) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
                System.out.print(i + " ");
                numberTurn = false;
                lock.notify();
            }
        }
    }

    public void printLetters() {
        for (char c = 'A'; c <= 'Z'; c++) {
            synchronized (lock) {
                while (numberTurn) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
                System.out.print(c + " ");
                numberTurn = true;
                lock.notify();
            }
        }
    }
}

In this code, one thread prints a number and switches the flag, the other prints a letter, and they alternate accordingly.