JAVA語言限時運行while迴圈的方法

來源:互聯網
上載者:User


需要通過一個while迴圈一直檢測一個感應器的狀態,並調整機器人姿態

但是這個while迴圈需要定時運行,大概運行10s後自動跳出

在網上找了半天,最終還是沒有找到什麼可用的解決方案

研究了一下,自己用date計算時間差解決了問題

while是最基本的迴圈,它的結構為:

while( 布林運算式 ) {
 //迴圈內容
}

只要布林運算式為true,迴圈體會一直執行下去。


原始碼


//初始設定變數
Date before=new Date();
Date now=new Date();
 
//定時迴圈
while(t<=10//迴圈時間){
 
            //計算迴圈總時間長度
            now = new Date();
            t = (now.getTime() - before.getTime())/1000;
 
            //迴圈內容
           
}
解析

before定義的是之前的時間

now是每次迴圈後當前的時間

t是時間差,單位是秒

例子

執行個體

public class Test {
   public static void main(String args[]) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}

以上執行個體編譯運行結果如下:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.