亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

每X秒打印一次“ hello world”

每X秒打印一次“ hello world”

catspeake 2019-10-25 14:52:55
最近我一直在使用帶有大量數字的循環來打印Hello World:int counter = 0;while(true) {    //loop for ~5 seconds    for(int i = 0; i < 2147483647 ; i++) {        //another loop because it's 2012 and PCs have gotten considerably faster :)        for(int j = 0; j < 2147483647 ; j++){ ... }    }    System.out.println(counter + ". Hello World!");    counter++;}我知道這是一種非常愚蠢的方法,但是我從來沒有在Java中使用過任何計時器庫。一個如何修改以上內容以每3秒打印一次?
查看完整描述

3 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

您還可以查看Timer和TimerTask類,這些類可用于計劃任務每秒鐘運行一次n。


您需要一個擴展TimerTask并覆蓋該public void run()方法的類,該類將在每次將該類的實例傳遞給timer.schedule()方法時執行。


這是一個示例,Hello World每5秒打印一次:-


class SayHello extends TimerTask {

    public void run() {

       System.out.println("Hello World!"); 

    }

}


// And From your main() method or any other method

Timer timer = new Timer();

timer.schedule(new SayHello(), 0, 5000);


查看完整回答
反對 回復 2019-10-25
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

如果要執行定期任務,請使用ScheduledExecutorService。特別是ScheduledExecutorService.scheduleAtFixedRate


編碼:


Runnable helloRunnable = new Runnable() {

    public void run() {

        System.out.println("Hello world");

    }

};


ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);


查看完整回答
反對 回復 2019-10-25
  • 3 回答
  • 0 關注
  • 656 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號