试图无限循环方法

时间:2016-07-03 15:45:36

标签: java infinite-loop

我只是好奇为什么我无法无限循环我的方法,当我尝试“while(true)”然后它工作,但如果我用我的对象“计数器”运行方法“function() “无限然后它仅适用于6200,有时它会将最大值更改为~6100或~6300,是否有人知道它为什么会这样工作并且可能如何?

public class Infinity {

  public static void main(String[] argv)
  {
    //Counter count = new Counter((short)0,(short)6180,(short)1);
    //count.startCounter(true);


    int a = 1;
    while (true) { 
      a = a + 1;
      System.out.println("Value: " + a);
    }
  }
}

这是我的主要课程

public class Counter 
{
  private short max;
  private short number;
  private short multiplicator;

  public Counter(short n,short m,short mp)
  {
    System.out.println("Implementing given numbers...");
    this.number=n;
    this.max=m;
    this.multiplicator=mp;
    System.out.println("");
  }

  public void startCounter(boolean b)
  {
    if (b == true) 
    {
    System.out.println("-----------------------------------");
    System.out.println("Starting counting from " + this.number + " to " + this.max);
    System.out.println("-----------------------------------");
    this.function();
    }
    else {
      System.out.println("Your Counter was set to false, abborting Start...");
    } 
  }

  public void function()
  {
    if (this.number < this.max) 
    {
      this.number = (short)(this.number + this.multiplicator);
      System.out.println("Number: " + this.number);
      this.function();
    } 
    else {
      System.out.println("Ending of Number");
    } 
  }
}

这是我的额外Counter类

2 个答案:

答案 0 :(得分:0)

你无法无限地运行你的循环,因为Java在堆栈中保存了Dinamically Enclosing Scope(DES)的激活记录(AR),但堆栈没有无限空间。

因此,为了避免使用你拥有的所有内存空间,Java会抛出StackOverflow错误。

答案 1 :(得分:-1)

您发布的代码不是循环,而是recursive函数调用。

Counter.function()视为黑匣子可能会有所帮助。当它被调用时,程序执行进入黑盒子并且不会返回到它之外直到该功能完成(即当它返回时)。

因此,当您第一次拨打function()时,您将进入一个黑匣子。然后,您再次从内部再次呼叫function() ,进入一个新的黑匣子。但是这里抓住了 - 你还没有退出第一个黑匣子!所以你最终得到这样的东西:

Executing function()
    Executing function()
        Executing function()
            ...etc...
        return;
    return;
return;

问题是,对于输入的每个黑盒子,Java需要分配内存on the stack,并且该内存不能被释放,直到功能(黑匣子)完成执行。结果,你最终会耗尽内存。

您应该做的是,正如您在问题中所建议的那样,使用循环:

public bool function() {
    if (this.number < this.max) {
        this.number = (short)(this.number + this.multiplicator);
        System.out.println("Number: " + this.number);
    } else {
        System.out.println("Ending of Number");
    }

    return (this.number < this.max);
}

要称之为你可以使用这样的东西:

while( function() )
    ;

或者这个:

while(true){
    if( !function() )
        break;
}

这允许在下一个函数调用开始之前完成一个函数调用。或者,为了继续黑盒子的类比,它看起来更像是这样:

Executing function()
return;
Executing function()
return;
Executing function()
return;
...etc...
相关问题