Reputation: 399
Attached is the code snippet below. I am new to multi-threading. Attempted to do multi threading which sort of works. However, after I click the button the first time, the second time onwards would not "create the thread" and run my method anymore.
I have also experimented with implementing the Runnable interface, but it could not get my Anchorpane reference to load the snackbar and hence I used the task method instead. Appreciate your help!
@FXML
private AnchorPane anchorPane;
Thread thread;
@FXML
void onClickLoginButton(ActionEvent event) throws Exception {
thread = new Thread(task);
thread.start();
}
Task<Void> task = new Task<Void>() {
@Override
public Void call(){
//System.out.println("Thread running"+thread.getId());
try {
credential = login.login();
} catch (UnknownHostException u) {
Platform.runLater(() -> {
System.out.println("No wifi");
JFXSnackbar snackbar = new JFXSnackbar(anchorPane);
snackbar.show("Please check your internet connection", 3000);
//u.printStackTrace();
});
} catch (Exception e) {
//e.printStackTrace();
}
//System.out.println("Thread running"+thread.getId());
return null;
}
};
Upvotes: 0
Views: 160
Reputation: 5563
The reason why this runs only once has to do with how Task
works in general
Per Task
's documentation here: https://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html
As with FutureTask, a Task is a one-shot class and cannot be reused. See Service for a reusable Worker.
Thus, if you want to repeat the said process multiple times, using a Task
is not a good choice. Check the recommended alternatives for workers and services in you want to achieve something like that.
Upvotes: 2