Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions twin/src/main/java/com/iluwatar/twin/BallThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Loading