简体   繁体   English

如何在 java 中跳出定时器循环

[英]How to break out of Timer Loop in java

I have this code where I loop a code using a timer, in which it would add or minus a random number.我有这段代码,我在其中使用计时器循环代码,它会在其中添加或减去随机数。 When the current number reaches below zero, it should print as "The Number is now in negative" an when it reaches 100 and above, it would print as "The Number reached 100+".当当前数字低于零时,它应该打印为“数字现在为负数”,当它达到 100 及以上时,它将打印为“数字达到 100+”。 Problem is, I want it to print only once if it fluctuates in negative or 100+ Here is my public void() method问题是,如果它以负数或 100+ 波动,我希望它只打印一次这是我的公共 void() 方法

   public void run() {
            
            Random myRand = new Random();
            int incdec = myRand.nextInt(2);//0 for Increasing 1 for Decreasing
            double change = myRand.nextInt(1000) / 100.0;//Random double number ranging up to 10.0
            
            if(incdec == 0){
                
                num=num+change;
                num= Math.round(num* 100.0) / 100.0;
                
                System.out.println("Increase: "+change );
                System.out.println("Current num: "+num);
                
             
                if(num>= 100){
                System.out.println("The Number reached 100+");
                }
                else if(num<= 0){
                     System.out.println("The Number is now in negative");     
                }
                System.out.println("");
                
            }

This one works but it would repeatedly print as it loops in public void run().这个可行,但它会在 public void run() 中循环时重复打印。

Simply cancel you timer from using只需取消使用计时器

  timer.cancel();

You can look at the answers for a very similar question: How to stop the task scheduled in java.util.Timer class .您可以查看一个非常相似的问题的答案: 如何停止在 java.util.Timer class 中安排的任务

I suppose your run method is inside a class that extends a TimerTask class so you can just cancel this task:我想您的run方法位于扩展TimerTask class 的 class 内,因此您可以取消此任务:

if (num >= 100) {
    System.out.println("The Number reached 100+");
    this.cancel();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM