Skip to content

Commit

Permalink
Fixed busy waiting in point iluwatar#2
Browse files Browse the repository at this point in the history
  • Loading branch information
TevaTavo committed Dec 7, 2024
1 parent b375919 commit 5721202
Showing 1 changed file with 29 additions and 21 deletions.
50 changes: 29 additions & 21 deletions twin/src/main/java/com/iluwatar/twin/BallThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -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
}
}

0 comments on commit 5721202

Please sign in to comment.