From 57212029408d05c96d7e1b84850f0037636d5677 Mon Sep 17 00:00:00 2001 From: Mustafa Muhhamed Date: Sat, 7 Dec 2024 16:14:00 +0200 Subject: [PATCH] Fixed busy waiting in point #2 --- .../java/com/iluwatar/twin/BallThread.java | 50 +++++++++++-------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/twin/src/main/java/com/iluwatar/twin/BallThread.java b/twin/src/main/java/com/iluwatar/twin/BallThread.java index 9d4d9cf71a76..fd777cdae59b 100644 --- a/twin/src/main/java/com/iluwatar/twin/BallThread.java +++ b/twin/src/main/java/com/iluwatar/twin/BallThread.java @@ -24,39 +24,45 @@ */ package com.iluwatar.twin; -import lombok.Setter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import lombok.extern.slf4j.Slf4j; /** - * This class is a UI thread for drawing the {@link BallItem}, and provide the method for suspend + * This class is a UI thread for drawing the {@link BallItem}, and provides methods for suspend * and resume. It holds the reference of {@link BallItem} to delegate the draw task. */ @Slf4j public class BallThread extends Thread { - @Setter - private BallItem twin; - - private volatile boolean isSuspended; + private static final Logger LOGGER = LoggerFactory.getLogger(BallThread.class); private volatile boolean isRunning = true; + private volatile boolean isSuspended = false; + private final Object lock = new Object(); + private final BallItem twin; - /** - * Run the thread. - */ - public void run() { + public BallThread(BallItem twin) { + this.twin = twin; + } - while (isRunning) { - if (!isSuspended) { - twin.draw(); + @Override + public void run() { + try { + while (isRunning) { + synchronized (lock) { + while (isSuspended) { + lock.wait(); + } + } + twin.doDraw(); twin.move(); - } - try { Thread.sleep(250); - } catch (InterruptedException e) { - throw new RuntimeException(e); } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); } } @@ -66,13 +72,15 @@ public void suspendMe() { } public void resumeMe() { - isSuspended = false; + synchronized (lock) { + isSuspended = false; + lock.notifyAll(); + } LOGGER.info("Begin to resume BallThread"); } public void stopMe() { - this.isRunning = false; - this.isSuspended = true; + isRunning = false; + resumeMe(); // Ensure the thread exits if it is waiting } } -