运行时未调用的打印方法,调试时调用

时间:2009-05-04 09:16:32

标签: java algorithm debugging

我用四种方法创建了一个类。我在其中插入了print语句,因此我可以看到它们是否正常工作。前三个没有问题。但是,当我调用第四种方法时,没有打印出来。奇怪的是,当我启动调试器并逐步遍历该方法时,将调用语句(并输出打印)。怎么会这样?

提前致谢。

有问题的方法:

   public void robin(int counter, int quant, int penalty) {

   if(Schedulers.quant==-1) {
      Schedulers.quant=quant;
   }


   while(p!=null && p.getArrival()==counter) {
       qrobin.add(p);

       if(i.hasNext())
           p=i.next();
       else {
           p=null;
           break;
       }
    }

   if(active!=null) {
       if(active.getLeftOver()>0 && Schedulers.quant>0) {
           active.decreaseLeftOver();
           Schedulers.quant--;
           System.out.print(active.getPID());
       }
       else if(active.getLeftOver()>0 && Schedulers.quant==0) {
           qrobin.add(active);
           active=qrobin.poll();

           Schedulers.quant=quant;
           Schedulers.quant--;

           if(active!=null) {
               System.out.print(active.getPID());
               active.decreaseLeftOver();
           }
           else
               System.out.print(" ");

       }
       else {
           active=qrobin.poll();

           Schedulers.quant=quant;
           Schedulers.quant--;


           if(active!=null) {
               System.out.print(active.getPID());
               active.decreaseLeftOver();
           }
           else
               System.out.print(" ");

       }
   }
   else {
       active=qrobin.poll();

       Schedulers.quant=quant;
       Schedulers.quant--;

       if(active!=null) {
          System.out.print(active.getPID());
          active.decreaseLeftOver(); 
       }
       else
           System.out.print(" ");
   }

}

代码调用它:

while(true){

        algorithm(algorithm,s,counter);

        counter++;
    }

5 个答案:

答案 0 :(得分:1)

看起来没有明显的答案,如果没有项目的其余部分,我们就无法重现和分析问题。

解决这种无法解释的行为的方法是在保留所述行为的同时尽可能地减少代码,即删除所有似乎与其无关的代码,看看问题是否仍然存在;如果不是,请添加一些代码,等等。最终,您应该能够确定导致问题的更改,并从中推断出实际发生的情况。

答案 1 :(得分:0)

发生这种情况有很多原因。但是,如果没有进一步的信息,几乎不可能帮助你。

答案 2 :(得分:0)

如果没有看到课程的其余部分,或者它使用的其他课程,我不能说任何确定的事情,但看起来它可能是竞争条件,即多个线程以不可预测的方式相互干扰。特别是多次使用Schedulers.quant,显然是一个非同步的静态变量,看起来非常可疑。

如果确实是竞争条件,您需要阅读this book然后返回并修复您的代码;多线程问题可能非常复杂,在编写多线程代码之前,您确实需要理解该理论。

答案 3 :(得分:0)

当你“运行”代码时,你是怎么做到的?它是否在某种服务器或容器中“运行”,其中标准输出可能会被重定向?这是我怀疑的。

使用System.out进行调试和故障排除可能会很麻烦并且(通常)是一种非常糟糕的做法 - 最好使用日志框架,例如log4j。这样您就不必猜测日志输出的发送位置。

答案 4 :(得分:0)

如果你的活动变量一直是空的,你只会打印“”,所以你可能不会在你的控制台输出中注意到它。这可能是一个计时问题,当你在debug中运行时,它不会为null。