1

谁能告诉我如何控制 java 的执行顺序,同时仍以简化、易于维护的结构组织代码?

我正在用java编写一个相当复杂的算法。一种方法长达数百行,以至于为了微调算法而隔离代码的关键部分变得过于劳动密集。为了简化代码,我确定了可以解析为单个变量的代码的每个部分,并将这些部分中的每个部分移到它们自己的方法中,然后从以前复杂的方法中调用这些方法。这很好,因为它使代码可读,并且更容易维护。

问题是现在我收到一些错误,表明调用方法在一些早期方法返回它们的值之前继续执行后续代码。

这是代码中的示例:

void myMethod(Double numb){  
    double first = new getFirst(numb);  
    double second = new getSecond(numb);  
    double third = new getThird(numb);  
    double anAside = new getAnAside(first, second, third);  
    double fourth = new getFourth(numb);  
}

getFourth(numb)出现的错误消息与我System.out.println()在 Eclipse 控制台中获得结果表明它getFirst(numb)仍在运行时同时发生的事情有关。当我拥有 , , , 和 within 的所有内容时getFirst(numb)getSecond(numb)getThird(numb)getAnAside(first,second,third)没有getFourth(numb)得到myMethod(numb)相同的证据表明代码块乱序运行。(因为它们没有子方法,所以代码都在一个长块中。)但是,代码很难阅读。如何对myMethod(numb)上面进行更改,以便在继续下一个方法之前必须完全返回每个方法,以便我仍然可以拥有易于阅读的代码?

4

3 回答 3

1

尝试在每个方法之间刷新 System.out,如下所示:

void myMethod(Double numb)
{  
    double first = new getFirst(numb);
    System.out.flush();
    double second = new getSecond(numb);
    System.out.flush();
    double third = new getThird(numb);
    System.out.flush();
    double anAside = new getAnAside(first, second, third);
    System.out.flush();
    double fourth = new getFourth(numb);  
}

As Matt B mentions, if you are only using one thread then it is probably something faulty with your logging.

于 2013-04-23T20:48:23.527 回答
1

I usually find that in terms of program structure, algorithms are never as complicated as people make them out to be. All you have to do is talk it out and write as you go. Say my fridge needs milk so that I need an algorithm to go get milk in the store:

public Milk goGetMilk(){
    getMoney();
    getCarKey();
    driveToStore();
    findMilk();
    buyMilk();
    driveBack();
    putMilkInFridge();
}

Then each nested method can in turn be broken into chuncks until I have a complete program.

As far as order of execution goes, if you have one thread: it's impossible to have racing conditions. If you are using multiple threads, you need to synchronize shared resources and rendezvous points.

于 2013-04-23T20:51:10.457 回答
1

This is a bit of guesswork, but I have known IDEs to display stdout output in the wrong order. I suggest you eliminate this first (even if it is unlikely), either by running Java from a proper terminal or writing the logs to disk.

于 2013-04-23T23:05:09.083 回答