如何从最后一个故障点重新启动方法



我有这样的方法:

    public void runMethod()
    {
    method1();
    method2();
    method3();
    }

我想根据ID多次调用此RunMethod。但是,如果Say Method2()出于某种原因失败,那么当我调用RunMethod时,它应该执行Method3(),而不是尝试再次执行Method1()(已为此ID成功运行)。

实现这一目标的最佳方法是什么?

非常感谢您的帮助

您可以在地图中记录是否已成功执行。

private Map<String, Boolean> executes = new HashMap<String, Boolean>();
public void method1() {
    Boolean hasExecuted = executes.get("method1");
    if (hasExecuted != null && hasExecuted) {
        return;
    }
    executes.put("method1", true);
    ...
}
// and so forth, with method2, method3, etc

您正在寻找某种状态机。将方法执行的状态保持在数据结构(例如地图)中。

在方法开始时,您需要检查是否成功执行Method1的执行方法。

public void runMethod()
{
  method1();
  method2()
  method3();
}
private Set<Integer> method1Executed = new HashSet<Integer>();
private Set<Integer> method2Executed = new HashSet<Integer>();
private void method1(Integer id)
{
    if (method1Executed.contains(id)) {
        return;
    }
    // Processing. 
    method1Executed.add(id)
}
 // Similar code for method2.

我的解决方案是添加int是指示灯,而不是引入地图,尤其是在经常调用代码的情况下。看起来像这样:

public int runMethod(int flag) {
    if (flag < 1) {
        method1();
        if (method1failed) {
            return 1;
        }
    }
    if (flag < 2) {
        method2();
        if (method2failed) {
            return 2;
        }
    }
    if (flag < 3) {
        method3();
        if (method3failed) {
            return 3;
        }
    }
    return 4;
}

最新更新