首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 多線程交替打印完全指南:從 AB 交替到 N 線程有序協作

     編輯:Java 相關知識

經典面試題:兩線程交替打印 AB

需求:線程 A 打印「A」,線程 B 打印「B」,各 10 次,輸出 ABABAB...。核心在於共享狀態標誌位 + wait/notify 協作。

基礎實現(雙線程版)

public class PrintAB {
    public static void main(String[] args) {
        PrintService service = new PrintService();
        new Thread(() -> { for (int i = 0; i < 10; i++) service.printA(); }, "Thread-A").start();
        new Thread(() -> { for (int i = 0; i < 10; i++) service.printB(); }, "Thread-B").start();
    }
}

class PrintService {
    private boolean flag = true; // true 輪到 A,false 輪到 B

    public synchronized void printA() {
        while (!flag) wait();    // 非本輪等待
        System.out.print("A");
        flag = false;
        notify();                // 喚醒 B
    }

    public synchronized void printB() {
        while (flag) wait();     // 非本輪等待
        System.out.print("B");
        flag = true;
        notify();                // 喚醒 A
    }
}

進階:三線程有序打印 ABC

擴展為 N 線程需維護「誰的回合」狀態,推薦使用 int turn 或 boolean[] 標記,配合 notifyAll() 避免虛假喚醒導致死鎖。

三線程實現

class PrintABC {
    private int turn = 0; // 0:A, 1:B, 2:C

    public synchronized void printA() {
        while (turn != 0) wait();
        System.out.print("A");
        turn = 1;
        notifyAll();
    }
    public synchronized void printB() {
        while (turn != 1) wait();
        System.out.print("B");
        turn = 2;
        notifyAll();
    }
    public synchronized void printC() {
        while (turn != 2) wait();
        System.out.print("C");
        turn = 0;
        notifyAll();
    }
}

通用化 N 線程協作框架

利用 ReentrantLock + Condition 替代 synchronized,支援動態線程數、可配置輪次,代碼更清晰、擴展性更強:

class CyclicPrinter {
    private final int threadCount;
    private final Lock lock = new ReentrantLock();
    private final Condition[] conditions;
    private int current = 0;

    public CyclicPrinter(int n) {
        this.threadCount = n;
        this.conditions = new Condition[n];
        for (int i = 0; i < n; i++) conditions[i] = lock.newCondition();
    }

    public void print(int id, String content, int rounds) {
        for (int i = 0; i < rounds; i++) {
            lock.lock();
            try {
                while (current != id) conditions[id].await();
                System.out.print(content);
                current = (current + 1) % threadCount;
                conditions[current].signal();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }
}

核心設計原則總結

  • 高內聚:協作邏輯封裝於專用類(PrintService),業務線程僅調用。
  • 低耦合:線程間無直接引用,通過共享協調器交互。
  • 正確性:while 迴圈檢查條件防虛假喚醒;notifyAll 確保多線程場景無遺漏。

掌握「共享狀態 + 等待通知」模式,即可輕鬆應對各類線程有序協作問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved