首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

並行與順序混合任務調度:線程等待機制實現 UML 活動圖邏輯

     編輯:程式設計綜合問答

問題建模

根據 UML 活動圖:

  • 任務鏈 1:1 → 3 → 5
  • 任務鏈 2:2 → 4
  • 兩鏈並行執行
  • 任務 6 需等待 4 和 5 完成
  • 任務 7 獨立並行

解決方案:主線程 + 工作線程 + Join 等待

public class TaskScheduler {
    public static void main(String[] args) throws InterruptedException {
        // 共享同步對象
        final Object lock45 = new Object();
        final boolean[] done = {false, false}; // [任務4完成, 任務5完成]
        
        // 線程1:執行 1→3→5
        Thread t1 = new Thread(() -> {
            executeTask(1); executeTask(3); executeTask(5);
            synchronized (lock45) {
                done[1] = true;
                lock45.notifyAll();
            }
        });
        
        // 線程2:執行 2→4
        Thread t2 = new Thread(() -> {
            executeTask(2); executeTask(4);
            synchronized (lock45) {
                done[0] = true;
                lock45.notifyAll();
            }
        });
        
        // 線程3:執行 7(獨立)
        Thread t3 = new Thread(() -> executeTask(7));
        
        // 啟動所有線程
        t1.start(); t2.start(); t3.start();
        
        // 主線程等待 4 和 5 完成
        synchronized (lock45) {
            while (!done[0] || !done[1]) {
                lock45.wait();
            }
        }
        
        // 執行任務6
        executeTask(6);
        
        // 等待所有線程結束
        t1.join(); t2.join(); t3.join();
        System.out.println("所有任務完成");
    }
    
    static void executeTask(int n) {
        System.out.println("執行任務 " + n);
        try { Thread.sleep(100); } catch (InterruptedException e) {}
    }
}

現代 Java 更優雅寫法

CompletableFuture (Java 8+)

CompletableFuture chain1 = CompletableFuture.runAsync(() -> executeTask(1))
    .thenRunAsync(() -> executeTask(3))
    .thenRunAsync(() -> executeTask(5));

CompletableFuture chain2 = CompletableFuture.runAsync(() -> executeTask(2))
    .thenRunAsync(() -> executeTask(4));

CompletableFuture chain3 = CompletableFuture.runAsync(() -> executeTask(7));

// 等待 chain1 和 chain2 完成,再執行任務6
CompletableFuture.allOf(chain1, chain2).thenRunAsync(() -> executeTask(6));

// 等待所有完成
CompletableFuture.allOf(chain1, chain2, chain3).join();

CountDownLatch (Java 5+)

CountDownLatch latch45 = new CountDownLatch(2); // 等待任務4和5

new Thread(() -> { executeTask(1); executeTask(3); executeTask(5); latch45.countDown(); }).start();
new Thread(() -> { executeTask(2); executeTask(4); latch45.countDown(); }).start();
new Thread(() -> executeTask(7)).start();

latch45.await(); // 阻塞直到計數歸零
executeTask(6);

對比總結

方案優點缺點適用版本
Thread + wait/notify底層可控,無依賴代碼冗長,易出錯所有版本
CountDownLatch語義清晰,簡潔一次性計數器Java 5+
CompletableFuture鏈式調用,異常傳播,函數式學習曲線稍陡Java 8+

核心原則

  1. 識別同步點(圖中的汇聚節點)
  2. 並行鏈用獨立線程/任務
  3. 同步點用計數器/屏障/Future組合等待
  4. 避免輪詢,使用阻塞等待機制
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved