Reputation: 329
Lets say I have a task that looks like this and I want it to run till a user presses a button. But when the button is pressed I don't want the thread to break out immediately. I want it to complete whatever it is doing before returning. How can I make this happen?
task = new Service(){
@Override
protected Task createTask() {
System.out.println("Task created");
return new Task<Void>() {
@Override
protected Void call() throws Exception {
while(true) {
// Do stuff her
}
return null;
}
};
}
};
...
...
task.start();
Upvotes: 2
Views: 38
Reputation: 209553
Just cancel the task from the button, and check for cancellation. If you only check when the task has completed "whatever it is doing", it will complete that before cancelling. For example:
task = new Service(){
@Override
protected Task createTask() {
System.out.println("Task created");
return new Task<Void>() {
@Override
protected Void call() throws Exception {
while(!isCancelled()) {
// Do stuff here
}
return null;
}
};
}
};
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(e -> task.cancel());
Upvotes: 2