简体   繁体   中英

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+". Problem is, I want it to print only once if it fluctuates in negative or 100+ Here is my public void() method

   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().

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 .

I suppose your run method is inside a class that extends a TimerTask class so you can just cancel this task:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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