通过抽象类javafx关闭任务

时间:2017-10-12 07:59:46

标签: java javafx task

这是我的问题。我无法弄清楚通过另一个类关闭任务。我有一个抽象类,它为几个继承的类的fire方法。此方法将运行任务,并且出于不同的原因,用户可能会在需要更改参数或类似内容时启用此任务。看下面的片段:

public interface Service {

void runThread();

void stopThread();

}

这是类实现:

public class ServiceImpl extends AbstractService implements Service {

@Override
public void runThread() {
    System.out.println("run thread: impl class");
    super.run();
}

@Override
public void stopThread() {
    System.out.println("stop Thread");
    System.out.println("Thread is shutdown: " + super.exec.isShutdown());
    super.exec.shutdownNow();
    System.out.println("Thread is shutdown: " + super.exec.isShutdown());
}

}

将触发super.run()方法的抽象类:

public abstract class AbstractService {

protected ExecutorService exec = Executors.newSingleThreadExecutor();

public AbstractService() {
    super();
}

protected void run() {
    System.out.println("run thread: abstract class");

    Task<Void> task = new Task<Void>() {

        @Override
        protected Void call() throws Exception {
            for(int i = 0; i < 1000; i++) {
                Thread.sleep(100);
                updateMessage("Hello World: " + i);
            }

            updateMessage("done");
            return null;
        }

    };

    task.setOnRunning(s -> {
        Main.label.textProperty().bind(task.messageProperty());
    });

    task.setOnSucceeded(s -> {
        Main.label.textProperty().bind(task.messageProperty());
    });

    exec.submit(task);
}

}

实际上,它可以工作,如果用户点击按钮停止,exec.shutdownnow()将被触发,循环中的计数将被停止。

但我的问题是我想在另一个类中分隔 stopThread()方法,以便将停止操作命令为主调用。因为 ServiceImpl 只是一个继承自抽象类的类的示例,如果我有6或10个继承自抽象类的类,我不想为每个实现ServiceImpl 一个 stopThread()方法。所以我尝试了,结果非常奇怪,因为我的&#34;大师班 - &gt; StopServiceImpl&#34;触发 stopThread()方法,通过Thread的super.exec的状态是shutdown:false并且Thread是shutdown:true但是抽象类循环中的计数仍在计数...

是否有可能实现该功能,还是应该复制每个ServiceImpl中的代码以停止任务?

1 个答案:

答案 0 :(得分:0)

如果您向调度程序提交任务,则会返回Future<>。可以通过拨打cancel(mayInterruptIfRunning)取消Future<>

Future<?> future = scheduler.submit(task);
...
future.cancel(true); // Your task needs to check the 'interrupt' otherwise it'll just finish anyway.