Print Friendly, PDF & Email

We can find several ways to create a task ( with a Thread in Java) in second plane that checks and updates the state of our data model. I faced the problem to validate GUI form constantly in the background for an application created with JavaFX so hope my attempts can help some one.

I’ll simplify the code so you can get th idea on how to do it.

Old fashion Thread that sleeps

package codigosjava.modernizandohilos;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

/**
 * Created by Javatlacati on 08/02/2017.
 */
public class Aciago extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Thread miHilo = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Corriendo");
                while (true) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("ola soi un hilo :v");
                        }
                    });

                    try {
                        System.out.println("anuma me voi a dormir");
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        System.err.println("#PosMeMuero");
                        break;
                    }
                }
            }
        }
        );

        miHilo.setName("soy el mapa soy el mapa soy el mapa soy el mapa soy el mapa!");
        miHilo.setDaemon(true);
        miHilo.start();
    }
}