javamultithreadingjavafxshared-variable

javafx thread synchronization while true


I'm new to JavaFX and have some trouble with threads. My application has to do something like this (hard pseudocode):

start(){
  startLoop(); //new thread
  displayThingsSavedToSharedVariable();
}



loop(){
  while (true){
    doThings();
    saveThingsToSharedVariable();
  }
}

I want to display output from loop() in JavaFX GUI up to date, one per line in the terminal, but I don't know how to synchronize a thread with loop() with JavaFX thread. The shared variable is only an - not working - example of what I want to achieve, the main question is how to dynamically print text to JavaFX GUI from an infinite loop in another thread.


Solution

  • The correct way to update the javafx gui is to use Platform.runLater.

    String mytext = deriveText();
    Platform.runLater(()->{
        label.setText(mytext);
    });
    

    You could also consider using the Observable interface.