From db485b84c1de5372114d5d61ae78ca7cf3d869ec Mon Sep 17 00:00:00 2001 From: omraj shinde Date: Sat, 27 Dec 2025 22:21:40 +0530 Subject: [PATCH] fix busy waiting in ballthread wait/notify --- .../java/com/iluwatar/twin/BallThread.java | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/twin/src/main/java/com/iluwatar/twin/BallThread.java b/twin/src/main/java/com/iluwatar/twin/BallThread.java index 7768d3ebbb99..35c68fde7ddf 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallThread.java +++ b/twin/src/main/java/com/iluwatar/twin/BallThread.java @@ -41,33 +41,39 @@ public class BallThread extends Thread { private volatile boolean isRunning = true; /** Run the thread. */ - public void run() { + @Override +public synchronized void run() { - while (isRunning) { - if (!isSuspended) { - twin.draw(); - twin.move(); - } - try { - Thread.sleep(250); - } catch (InterruptedException e) { - throw new RuntimeException(e); + while (isRunning) { + try { + while (isSuspended) { + wait(); // ❗ block instead of polling } + twin.draw(); + twin.move(); + Thread.sleep(250); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; } } +} + public void suspendMe() { isSuspended = true; LOGGER.info("Begin to suspend BallThread"); } - public void resumeMe() { - isSuspended = false; - LOGGER.info("Begin to resume BallThread"); - } + public synchronized void resumeMe() { + isSuspended = false; + notify(); // ❗ wake up waiting thread + LOGGER.info("Begin to resume BallThread"); +} - public void stopMe() { - this.isRunning = false; - this.isSuspended = true; - } + public synchronized void stopMe() { + isRunning = false; + isSuspended = false; + notify(); // ensure thread exits if waiting +} }