发布时间:2025-12-09 11:52:09 浏览次数:1
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 taskworking on the taskworking on the taskworking on the taskworking on the taskworking on the taskworking on the taskstop 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 taskworking on the taskworking on the taskworking on the taskworking on the taskworking on the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the taskworking on the taskstop the task