Skip to content
Open
Show file tree
Hide file tree
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
33 changes: 24 additions & 9 deletions twin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,36 +88,51 @@ public class BallItem extends GameItem {
public class BallThread extends Thread {
@Setter
private BallItem twin;
private final Object lock = new Object();
private volatile boolean isSuspended;
private volatile boolean isRunning = true;

public void run() {
while (isRunning) {
if (!isSuspended) {
twin.draw();
twin.move();
}
try {
Thread.sleep(250);
synchronized (lock) {
// Wait to be notified instead of polling, so resuming takes effect immediately.
while (isSuspended && isRunning) {
lock.wait();
}
}
if (isRunning) {
twin.draw();
twin.move();
Thread.sleep(250);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

public void suspendMe() {
isSuspended = true;
synchronized (lock) {
isSuspended = true;
}
LOGGER.info("Begin to suspend BallThread");
}

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;
synchronized (lock) {
this.isRunning = false;
this.isSuspended = true;
lock.notifyAll();
}
}
}
```
Expand Down
34 changes: 25 additions & 9 deletions twin/src/main/java/com/iluwatar/twin/BallThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public class BallThread extends Thread {

@Setter private BallItem twin;

private final Object lock = new Object();

private volatile boolean isSuspended;

private volatile boolean isRunning = true;
Expand All @@ -44,30 +46,44 @@ public class BallThread extends Thread {
public void run() {

while (isRunning) {
if (!isSuspended) {
twin.draw();
twin.move();
}
try {
Thread.sleep(250);
synchronized (lock) {
// Wait to be notified instead of polling, so resuming takes effect immediately.
while (isSuspended && isRunning) {
lock.wait();
}
}
if (isRunning) {
twin.draw();
twin.move();
Thread.sleep(250);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

public void suspendMe() {
isSuspended = true;
synchronized (lock) {
isSuspended = true;
}
LOGGER.info("Begin to suspend BallThread");
}

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;
synchronized (lock) {
this.isRunning = false;
this.isSuspended = true;
lock.notifyAll();
}
}
}
Loading