我想在java.null中編寫一個定時器,它將執行以下操作: 程序啓動時,啓動定時器1,它將在45分鐘後停止,同時啓動第二個定時器,這將會在15分鐘後停止。此時第一個定時器將再次啓動,並重覆上述循環,直到程序退出 第一個定時器:45分鐘(我可以使用計算機的時間) 第二個定時器:15分鐘(暫停時間) 第一個定時器:45分鐘(時間我可以使用計算機) 第二定時器:15分鐘(暫停時間) 第一定時器:45分鐘(我可以使用計算機的時間) 第二定時器:15分鐘(暫停時間)Java如何編寫定時器
我不知道如何使用線程和定時器(utils,swing),所以我試圖使用while(true),但CPU上升。 這裏是我當前的代碼
static int getMinute(){
Calendar cal=Calendar.getInstance();
int minute=cal.getTime().getMinutes();
return minute;
}
public static Runnable clockf(){
if (endTime>=60){
endTime=endTime-60;}
System.out.println(startTime);
System.out.println(currentTime);
System.out.println(endTime);
if(currentTime==endTime){
pauseStart=getMinute();
currentTime=getMinute();
pauseEnd=pauseStart+15;
if(currentTime==pauseEnd){
pauseStart=0;
pauseEnd=0;
startTime=getMinute();
currentTime=getMinute();
endTime=startTime+45;
}
}
else{
update();
}
return null;
}
private static void update() {
currentTime=getMinute();
System.out.println(currentTime);
}
public static void main(String[] args) {
startTime=getMinute();
currentTime=getMinute();
endTime=startTime+45;
Thread t=new Thread(clockf());
t.setDaemon(true);
t.start();
try {
Thread.currentThread().sleep(1000);//60000
} catch (InterruptedException e) {
System.err.println(e);
}
}
,但它不是很好。有沒有辦法讓clockf方法只運行一次/分鐘? 或任何其他方式來使該計時器運行?