是否可以创建一个方法,可以通过“返回”来暂时暂停自身,然后在再次调用时恢复?它应该表现得好像它从未返回(即保留其所有变量,继续执行下一行等)。
public static void main(String args) {
method(); //should start method
//do stuff ONLY AFTER method() RETURNS
method(); //should continue method at same place as it ended
//do more stuff ONLY AFTER method() RETURNS
}
private static void method() {
while(true) {
//do stuff
return;
//do different stuff
return;
//do a third thing
return;
//then start all over
}
}
我在 StackOverflow 上看到了一些类似的问题,但没有一个答案似乎足够或具有解释性。
最佳答案
你要找的类似于C#的yield return语句: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
据我所知,Java 没有类似的构造。如果你真的很绝望并且不畏惧大量的字节码操作,你可以自己做一些事情:
首先创建一个具有名为yieldReturn() 的静态方法的类。然后,您可以搜索所有类以查找对该方法的调用,并按照 http://csharpindepth.com/articles/chapter6/iteratorblockimplementation.aspx 执行修改。
关于java - 暂时暂停方法直到下次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473454/