Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
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 42 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");
}
Comment on lines 63 to 66
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suspendMe() is currently not synchronized, while run() is. This can create visibility issues for isSuspended updates across threads. Make suspendMe() synchronized (or declare isSuspended as volatile) to ensure the suspension request is observed by the running thread.


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
Morty Proxy This is a proxified and sanitized view of the page, visit original site.