Timer類的cancel()方法用於終止此計時器並刪除任何當前計劃的任務。
用法:
public void cancel()
參數:該函數不接受任何參數。
返回值:該方法沒有返回值。
異常:該函數不會引發任何異常。
下麵的程序演示了上述函數:
程序1:
// program to demonstrate the
// function java.util.Timer.cancel()
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating timertask, timer
Timer timer = new Timer();
TimerTask tt = new TimerTask() {
public void run()
{
for (int i = 1; i <= 15; i++) {
System.out.println("working on the task");
if (i >= 7) {
System.out.println("stop the task");
// loop stops after 7 iterations
timer.cancel();
break;
}
}
};
};
timer.schedule(tt, 1000, 1000);
}
}
輸出:
working on the task working on the task working on the task working on the task working on the task working on the task working on the task stop the task
程序2:
// program to demonstrate the
// function java.util.Timer.cancel()
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating timertask, timer
Timer timer = new Timer();
TimerTask tt = new TimerTask() {
public void run()
{
for (int i = 1; i <= 15; i++) {
System.out.println("working on the task");
if (i >= 7) {
System.out.println("stop the task");
// loop stops after 7 iterations
timer.cancel();
}
}
};
};
timer.schedule(tt, 1000, 1000);
}
}
輸出:
working on the task working on the task working on the task working on the task working on the task working on the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task working on the task stop the task
相關用法
- Java Timer purge()用法及代碼示例
- Java Java.util.Timer用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java lang.Long.builtcount()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Clock tickMinutes()用法及代碼示例
- Java Clock withZone()用法及代碼示例
注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 Timer cancel() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。