2424 */
2525package com .iluwatar .twin ;
2626
27- import lombok .Setter ;
27+ import org .slf4j .Logger ;
28+ import org .slf4j .LoggerFactory ;
2829import lombok .extern .slf4j .Slf4j ;
2930
3031/**
31- * This class is a UI thread for drawing the {@link BallItem}, and provide the method for suspend
32+ * This class is a UI thread for drawing the {@link BallItem}, and provides methods for suspend
3233 * and resume. It holds the reference of {@link BallItem} to delegate the draw task.
3334 */
3435
3536@ Slf4j
3637public class BallThread extends Thread {
3738
38- @ Setter
39- private BallItem twin ;
40-
41- private volatile boolean isSuspended ;
39+ private static final Logger LOGGER = LoggerFactory .getLogger (BallThread .class );
4240
4341 private volatile boolean isRunning = true ;
42+ private volatile boolean isSuspended = false ;
43+ private final Object lock = new Object ();
44+ private final BallItem twin ;
4445
45- /**
46- * Run the thread.
47- */
48- public void run () {
46+ public BallThread (BallItem twin ) {
47+ this .twin = twin ;
48+ }
4949
50- while (isRunning ) {
51- if (!isSuspended ) {
52- twin .draw ();
50+ @ Override
51+ public void run () {
52+ try {
53+ while (isRunning ) {
54+ synchronized (lock ) {
55+ while (isSuspended ) {
56+ lock .wait ();
57+ }
58+ }
59+ twin .doDraw ();
5360 twin .move ();
54- }
55- try {
5661 Thread .sleep (250 );
57- } catch (InterruptedException e ) {
58- throw new RuntimeException (e );
5962 }
63+ } catch (InterruptedException e ) {
64+ Thread .currentThread ().interrupt ();
65+ throw new RuntimeException (e );
6066 }
6167 }
6268
@@ -66,13 +72,15 @@ public void suspendMe() {
6672 }
6773
6874 public void resumeMe () {
69- isSuspended = false ;
75+ synchronized (lock ) {
76+ isSuspended = false ;
77+ lock .notifyAll ();
78+ }
7079 LOGGER .info ("Begin to resume BallThread" );
7180 }
7281
7382 public void stopMe () {
74- this . isRunning = false ;
75- this . isSuspended = true ;
83+ isRunning = false ;
84+ resumeMe (); // Ensure the thread exits if it is waiting
7685 }
7786}
78-
0 commit comments