Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed busy waiting in point #2 #3122

Closed
wants to merge 2 commits into from
Closed
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
61 changes: 41 additions & 20 deletions twin/src/main/java/com/iluwatar/twin/BallThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,55 +24,76 @@
*/
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();
twin.move();
}
try {
Thread.sleep(250);
} catch (InterruptedException e) {
throw new RuntimeException(e);
@Override
public void run() {
try {
while (isRunning) {
if (isSuspended) {
synchronized (lock) {
lock.wait();
}
} else {
twin.doDraw();
twin.move();
Thread.sleep(250);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}

/**
* Suspend the thread.
*/
public void suspendMe() {
isSuspended = true;
LOGGER.info("Begin to suspend BallThread");
}

/**
* Notify run to resume.
*/
public void resumeMe() {
isSuspended = false;
LOGGER.info("Begin to resume BallThread");
synchronized (lock) {
lock.notifyAll();
}
}

/**
* Stop running thread.
*/
public void stopMe() {
this.isRunning = false;
this.isSuspended = true;
synchronized (lock) {
lock.notifyAll();
}
}
}

Loading