title: Java FX Thread Safe Pause/Sleep
body: <p>I have a JavaFX application, within it are about 20 labels. When a user clicks a label, I need the label to flash red. To make the label flash red, I am using a thread I actually developed for swing but converted to JavaFX. It worked for awhile, but I've recently traced the application lock-ups to the animation of the label. The way I did the animation was simple:</p>
  
  <pre><code>new Thread(new AnimateLabel(tl,idx)).start();
  </code></pre>
  
  <p>tl points to an ArrayList of labels, and idx to the index of it. Another label has an on click event attached to it, and when you click, it creates the thread that animates the label (makes it flash).</p>
  
  <p>For some reason, this will cause the application to lock up if there's a lot of labels being pressed.</p>
  
  <p>I'm pretty sure it's a thread safety issue with JavaFX. I have another thread that shares the JavaFX application thread as so:</p>
  
  <pre><code>TimerUpdater tu = new TimerUpdater(mDS);
  Timeline incHandler = new Timeline(new KeyFrame(Duration.millis(130),tu)); 
  incHandler.setCycleCount(Timeline.INDEFINITE); 
  incHandler.play(); 
  </code></pre>
  
  <p>TimerUpdater will constantly update the text on labels, even the ones that are flashing.</p>
  
  <p>Here's the label animator:</p>
  
  <pre><code>private class AnimateLabel implements Runnable
  {
      private Label lbl;
      public AnimateLabel(Label lbl, int myIndex)
      {
          // if inAnimation.get(myIndex) changes from myAnim's value, stop,
          // another animation is taking over
          this.lbl = lbl;
      }
  
      @Override
      public void run() {
          int r, b, g;
          r=255;
          b=0;
          g=0;
  
          int i = 0;
          while(b &lt;= 255 &amp;&amp; g &lt;= 255)
          {
              RGB rgb = getBackgroundStyle(lbl.getStyle());
              if(rgb != null)
              {
                  if(rgb.g &lt; g-16) { return; }
              }
              lbl.setStyle("-fx-color: #000; -fx-background-color: rgb("+r+","+g+","+b+");");
              try { Thread.sleep(6); }
              catch (Exception e){}
              b += 4;
              g += 4;
              ++i;
          }
          lbl.setStyle("-fx-color: #000; -fx-background-color: fff;");
      }
  }
  </code></pre>
  
  <p>I would run this as such:</p>
  
  <pre><code>javafx.application.Platform.runLater(new AnimateLabel(tl, idx));
  </code></pre>
  
  <p>However, Thread.sleep(6) will be ignored. Is there a way to pause in a run later to control the speed of the animation while sharing a thread with javafx.application?</p>
  
  <p>Regards,
  Dustin</p>