问题
How I can stop a service or thread safely for prevent an IO exception? I have tried with the method cancel, but this isn't work. What is the guidelines ?
回答1:
You have to check if cancel was requested inside your Task-Loop:
package test;
import javafx.concurrent.Task;
public class TestTask extends Task<String>
{
@Override
protected String call() throws Exception
{
StringBuilder builder = new StringBuilder();
int max = 1000;
for (int i = 0; i < max; i++)
{
if (isCancelled())
{
throw new InterruptedException();
}
builder.append(i);
updateProgress(i, max - 1);
}
return builder.toString();
}
}
来源:https://stackoverflow.com/questions/43919754/how-can-i-kill-a-service-or-task-in-javafx