如何终止JavaFx中的服务或任务? [英] How can I kill a service or task in JavaFx?

查看:122
本文介绍了如何终止JavaFx中的服务或任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何安全地停止服务或线程以防止IO异常?我已经尝试过使用方法cancel,但这是行不通的.指导原则是什么?

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 ?

推荐答案

您必须检查任务循环中是否请求取消:

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();
    }
}

这篇关于如何终止JavaFx中的服务或任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆