File tree Expand file tree Collapse file tree 1 file changed +24
-18
lines changed
twin/src/main/java/com/iluwatar/twin Expand file tree Collapse file tree 1 file changed +24
-18
lines changed Original file line number Diff line number Diff line change @@ -41,33 +41,39 @@ public class BallThread extends Thread {
4141 private volatile boolean isRunning = true ;
4242
4343 /** Run the thread. */
44- public void run () {
44+ @ Override
45+ public synchronized void run () {
4546
46- while (isRunning ) {
47- if (!isSuspended ) {
48- twin .draw ();
49- twin .move ();
50- }
51- try {
52- Thread .sleep (250 );
53- } catch (InterruptedException e ) {
54- throw new RuntimeException (e );
47+ while (isRunning ) {
48+ try {
49+ while (isSuspended ) {
50+ wait (); // ❗ block instead of polling
5551 }
52+ twin .draw ();
53+ twin .move ();
54+ Thread .sleep (250 );
55+ } catch (InterruptedException e ) {
56+ Thread .currentThread ().interrupt ();
57+ break ;
5658 }
5759 }
60+ }
61+
5862
5963 public void suspendMe () {
6064 isSuspended = true ;
6165 LOGGER .info ("Begin to suspend BallThread" );
6266 }
6367
64- public void resumeMe () {
65- isSuspended = false ;
66- LOGGER .info ("Begin to resume BallThread" );
67- }
68+ public synchronized void resumeMe () {
69+ isSuspended = false ;
70+ notify (); // ❗ wake up waiting thread
71+ LOGGER .info ("Begin to resume BallThread" );
72+ }
6873
69- public void stopMe () {
70- this .isRunning = false ;
71- this .isSuspended = true ;
72- }
74+ public synchronized void stopMe () {
75+ isRunning = false ;
76+ isSuspended = false ;
77+ notify (); // ensure thread exits if waiting
78+ }
7379}
You can’t perform that action at this time.
0 commit comments