Call to 'Thread.sleep()' in a loop, probably busy-waiting

Call to ‘Thread.sleep()’ in a loop, probably busy-waiting

Call to ‘Thread.sleep()’ in a loop, probably busy-waiting

Call to ‘Thread.sleep()’ in a loop, probably busy-waiting

這個警告是在提醒你程式碼中可能存在「忙碌等待」(busy-waiting) 的問題。

什麼是忙碌等待?
當你在迴圈中使用 Thread.sleep() 時,通常是在等待某個條件改變,像這樣:
java// 有問題的寫法
while (!條件滿足) {
Thread.sleep(100); // 每100毫秒檢查一次
// 檢查條件…
}
為什麼這樣不好?

浪費CPU資源 - 不斷地醒來檢查條件
延遲不精確 - 可能錯過條件改變的時機
效能不佳 - 不必要的輪詢操作

更好的解決方案

  1. 使用 wait() 和 notify()
    synchronized (鎖物件) {
    while (!條件滿足) {
    鎖物件.wait(); // 有效率地等待通知
    }
    }

// 在其他地方條件改變時
synchronized (鎖物件) {
// 改變條件
鎖物件.notify(); // 通知等待的執行緒
}
2. 使用 CountDownLatch
CountDownLatch latch = new CountDownLatch(1);

// 等待執行緒
latch.await(); // 阻塞直到條件滿足

// 在其他地方
latch.countDown(); // 釋放等待
3. 使用 BlockingQueue
BlockingQueuequeue = new ArrayBlockingQueue<>(10);

// 消費者 - 會阻塞等待
String item = queue.take(); // 沒有元素時會等待

// 生產者
queue.put(“資料”); // 會喚醒等待的消費者
4. 週期性任務使用 ScheduledExecutorService
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

// 每秒執行一次,而不是用sleep迴圈
executor.scheduleAtFixedRate(() -> {
// 你的任務
}, 0, 1, TimeUnit.SECONDS);
關鍵差異

忙碌等待:主動輪詢,浪費資源
正確做法:被動等待,有事件時才被喚醒

這樣可以讓程式更有效率,響應更即時!