Java Timer cancel()实例讲解

时间:2022-04-06
本文章向大家介绍Java Timer cancel()实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

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