Skip to content

Commit 23a95d1

Browse files
committed
fixing-busy waiting loop #BallThread
1 parent dacb230 commit 23a95d1

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

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

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
*
77
* Permission is hereby granted, free of charge, to any person obtaining a copy
88
* of this software and associated documentation files (the "Software"), to deal
9-
* in the Software without restriction, including but not limited to the rights
9+
* in the Software without restriction, including without limitation the rights
1010
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1111
* copies of the Software, and to permit persons to whom the Software is
1212
* furnished to do so, subject to the following conditions:
@@ -55,15 +55,14 @@ public BallThread(BallItem twin) {
5555
public void run() {
5656
try {
5757
while (isRunning) {
58-
if (isSuspended) {
59-
synchronized (lock) {
58+
synchronized (lock) {
59+
while (isSuspended) {
6060
lock.wait();
6161
}
62-
} else {
63-
twin.doDraw();
64-
twin.move();
65-
Thread.sleep(250);
6662
}
63+
twin.doDraw();
64+
twin.move();
65+
Thread.sleep(250);
6766
}
6867
} catch (InterruptedException e) {
6968
Thread.currentThread().interrupt();
@@ -83,21 +82,18 @@ public void suspendMe() {
8382
* Notify run to resume.
8483
*/
8584
public void resumeMe() {
86-
isSuspended = false;
87-
LOGGER.info("Begin to resume BallThread");
8885
synchronized (lock) {
86+
isSuspended = false;
8987
lock.notifyAll();
9088
}
89+
LOGGER.info("Begin to resume BallThread");
9190
}
9291

9392
/**
9493
* Stop running thread.
9594
*/
9695
public void stopMe() {
97-
this.isRunning = false;
98-
this.isSuspended = true;
99-
synchronized (lock) {
100-
lock.notifyAll();
101-
}
96+
isRunning = false;
97+
resumeMe(); // Ensure the thread exits if it is waiting
10298
}
10399
}

0 commit comments

Comments
 (0)