Concurrency_WorkerThread1
  • After sleeping for three seconds "Thread.sleep(3000)", the worker thread calls the runLater() method of the javafx.application.
  • Platform.runLater(() -> label1.setText(status));
Code Used:

//Exception in thread "Thread-4" java.lang.IllegalStateException:
//Not on FX application thread; currentThread = Thread-4
package javafxtemplate1;
//Grid_VBOx_Thread
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTemplate1 extends Application {
Label label1 = new Label("l1");
TextArea result1 = new TextArea();

Button startBtn = new Button("Start");
Button exitBtn = new Button("Exit");
@Override
public void start(Stage primaryStage) {
//
result1.setMaxWidth(350);
result1.setMinHeight(250);
result1.setLayoutY(20);
startBtn.setMinWidth(50);
exitBtn.setMinWidth(50);
startBtn.setOnAction(e -> startTask());
exitBtn.setOnAction(e -> primaryStage.close());

HBox hBox = new HBox(10, startBtn, exitBtn, label1);
VBox vBox = new VBox(10, result1);
//
GridPane root = new GridPane();
// TilePane root = new TilePane();
root.setVgap(10);root.setHgap(10);
root.add(hBox,0,0,1,1);
root.add(vBox,1,1,2,1);
//
Scene scene = new Scene(root, 450,400);
primaryStage.setScene(scene);
primaryStage.setTitle("Slider::Grid");
primaryStage.show();
}
//
public static void main(String[] args) {
Application.launch(args);
}
public void startTask() {
// Create a Runnable
Runnable task = () -> runTask();
// Run the task in a background thread
Thread backgroundThread = new Thread(task);
// Terminate the running thread if the application exits
label1.setText(backgroundThread.getName());
backgroundThread.setDaemon(true);
// Start the thread
backgroundThread.start();
}

public void runTask() {
for(int i = 1; i <= 10; i++) {
try {
//final String status = "Processing " + i + " of " + 10+"\n";
String status = "Processing " + i + " of " + 10+"\n";
result1.appendText(status + " "+ Thread.currentThread().getName());
//label1.setText(status);// throws Thread -4 Error,Not on FX application thread;
Platform.runLater(() -> label1.setText(status));
Thread.sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
result1.appendText("Thread completed");
}
}
 

Exception Error:

Note label1 setText won't show any updates:

 

 

Resolves with runLater()