📜  Java中的定时器 cancel() 方法及示例

📅  最后修改于: 2022-05-13 01:54:43.090000             🧑  作者: Mango

Java中的定时器 cancel() 方法及示例

Timer 类cancel()方法用于终止此计时器并删除任何当前计划的任务。

句法:

public void cancel()

参数:该函数不接受任何参数。

返回值:该方法没有返回值。

异常:该函数不抛出任何异常。

下面的程序演示了上述函数:

方案一:

// 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

方案二:

// 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