Skip to content

Commit f67310b

Browse files
committed
Fixed busy waiting in point 2
1 parent 5721202 commit f67310b

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

twin/src/main/java/com/iluwatar/twin/BallThread.java

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,36 +51,49 @@ public BallThread(BallItem twin) {
5151
public void run() {
5252
try {
5353
while (isRunning) {
54-
synchronized (lock) {
55-
while (isSuspended) {
54+
if (isSuspended) {
55+
synchronized (lock) {
5656
lock.wait();
5757
}
58+
} else {
59+
twin.doDraw();
60+
twin.move();
61+
Thread.sleep(250);
5862
}
59-
twin.doDraw();
60-
twin.move();
61-
Thread.sleep(250);
6263
}
6364
} catch (InterruptedException e) {
6465
Thread.currentThread().interrupt();
6566
throw new RuntimeException(e);
6667
}
6768
}
6869

70+
/**
71+
* Suspend the thread.
72+
*/
6973
public void suspendMe() {
7074
isSuspended = true;
7175
LOGGER.info("Begin to suspend BallThread");
7276
}
7377

78+
/**
79+
* Notify run to resume.
80+
*/
7481
public void resumeMe() {
82+
isSuspended = false;
83+
LOGGER.info("Begin to resume BallThread");
7584
synchronized (lock) {
76-
isSuspended = false;
7785
lock.notifyAll();
7886
}
79-
LOGGER.info("Begin to resume BallThread");
8087
}
8188

89+
/**
90+
* Stop running thread.
91+
*/
8292
public void stopMe() {
83-
isRunning = false;
84-
resumeMe(); // Ensure the thread exits if it is waiting
93+
this.isRunning = false;
94+
this.isSuspended = true;
95+
synchronized (lock) {
96+
lock.notifyAll();
97+
}
8598
}
8699
}

0 commit comments

Comments
 (0)