代碼枚舉串口並打印,結果每個端口信息重複出現 5 次。
int x = 0;
Enumeration portList1 = CommPortIdentifier.getPortIdentifiers();
while (portList1.hasMoreElements()) {
x++;
test_buffer[x] = ((CommPortIdentifier) portList1.nextElement()).getName();
System.out.println("第" + x + "串口" + test_buffer[x]);
// ...
}
test_1 = new String[x];
for (int j = 0; j < x; j++) {
test_1[j] = test_buffer[j+1];
System.out.println("第" + j + "串口:" + test_1[j]);
}
輸出顯示:
第1串口COM1 ... 第4串口LPT2(第一輪)
第0串口:COM1 ... 第3串口:LPT2(第二輪)
然後整個雙輪輸出重複 5 次。
此枚舉代碼被放在一個外層循環或定時器/監聽器回調中,每次觸發執行一次,共觸發 5 次。單次執行邏輯正常(輸出兩輪:1-base 和 0-base),但外層重複調用導致整體重複 5 次。
while(true)、TimerTask、SerialPortEventListener、按鈕點擊事件中被多次觸發。private static boolean enumerated = false;
public void enumeratePorts() {
if (enumerated) return;
enumerated = true;
// 枚舉邏輯
}