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

[JAVA100例] 第64例:線程間通訊——共享標誌位協作繪製三角形

     編輯:Java 相關知識

本例演示兩個線程通過共享 static int flag 協作繪製實心三角形:線程 1 輸出每行前導空格,線程 2 輸出星號並換行,輪流執行形成三角形。

核心代碼

public class mainThread {
  public static int flag = 0;  // 共享協作標誌
  int count = 10;

  public static void main(String[] arg) { new mainThread(); }

  mainThread() {
    thread1 t1 = new mainThread.thread1(this.count);
    thread2 t2 = new mainThread.thread2(this.count);
    t1.start(); t2.start();
    flag = 1;  // 讓線程 1 先執行
  }

  class thread1 extends Thread {
    int count1 = 0;
    thread1(int i) { count1 = i; }
    public void run() {
      while (true) {
        if (count1 <= 0) break;
        if (mainThread.flag == 1) {
          for (int i = 0; i < count1; i++) System.out.print(" ");
          count1--;
          mainThread.flag = 2;  // 交棒給線程 2
        }
      }
    }
  }

  class thread2 extends Thread {
    int count2 = 0;
    thread2(int i) { count2 = i; }
    public void run() {
      int count = 0;
      while (true) {
        if (count >= count2) break;
        if (mainThread.flag == 2) {
          for (int i = 0; i < (count * 2 + 1); i++) System.out.print("*");
          System.out.print("\n");
          count++;
          mainThread.flag = 1;  // 交棒給線程 1
        }
      }
    }
  }
}

輸出效果

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

機制分析與缺陷

正確的線程通訊模式

// 1. wait/notify(經典)
synchronized(lock) {
  while (!condition) lock.wait();
  // do work
  condition = false;
  lock.notifyAll();
}

// 2. BlockingQueue(生產者消費者)
BlockingQueue queue = new LinkedBlockingQueue<>();
// 生產者 queue.put(task)
// 消費者 queue.take()

// 3. CompletableFuture(異步編排)
CompletableFuture.supplyAsync(() -> ...)
  .thenApplyAsync(...)
  .thenAccept(...);

// 4. CyclicBarrier/CountDownLatch(階段同步)

現代最佳實踐

  • 共享標誌必須 volatile:private volatile int flag = 0;
  • 優先使用 高級併發組件 而非手動 wait/notify
  • 避免忙等待,使用阻塞隊列或鎖條件變量
  • 結構化併發 StructuredTaskScope (JDK 21+) 自動管理子任務生命週期
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方面說明
同步機制忙等待 + 共享變量輪詢
可見性flag 未聲明 volatile,多核 CPU 可能不可見(JIT 可能優化導致無限循環)
CPU 佔用極高(空循環輪詢)
線程安全非原子操作,flag 讀寫可能競爭
死鎖風險若一線程異常退出,另一線程永久等待