本例演示兩個線程通過共享 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
}
}
}
}
}
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
| 方面 | 說明 |
|---|---|
| 同步機制 | 忙等待 + 共享變量輪詢 |
| 可見性 | flag 未聲明 volatile,多核 CPU 可能不可見(JIT 可能優化導致無限循環) |
| CPU 佔用 | 極高(空循環輪詢) |
| 線程安全 | 非原子操作,flag 讀寫可能競爭 |
| 死鎖風險 | 若一線程異常退出,另一線程永久等待 |