How can I kill a service or task in JavaFx?

南笙酒味 提交于 2019-12-12 04:36:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!