簡體   English   中英

如何在 java 中跳出定時器循環

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

我有這段代碼,我在其中使用計時器循環代碼,它會在其中添加或減去隨機數。 當當前數字低於零時,它應該打印為“數字現在為負數”,當它達到 100 及以上時,它將打印為“數字達到 100+”。 問題是,如果它以負數或 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("");
                
            }

這個可行,但它會在 public void run() 中循環時重復打印。

只需取消使用計時器

  timer.cancel();

您可以查看一個非常相似的問題的答案: 如何停止在 java.util.Timer class 中安排的任務

我想您的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