📜  Java中的计时器 purge() 方法及示例

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

Java中的计时器 purge() 方法及示例

Java中Timer 类purge()方法用于从 Timer 的这个队列中移除所有取消的任务。时间的行为不受调用此方法的影响。

句法:

public int purge()

参数:该方法不带任何参数。

返回值:该方法返回已从队列中移除的任务数

下面的程序说明了Java中 purge() 方法的工作原理:

方案一:

// Java code to illustrate purge()
  
import java.util.*;
  
public class Java_Timer_Demo {
    public static void main(String args[])
    {
  
        // Creating the timer task, timer
        Timer time = new Timer();
  
        TimerTask timetask = 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("Stopping the task");
                        time.cancel();
                        break;
                    }
                }
  
                // purging the timer
                System.out.println("The Purge value:"
                                   + time.purge());
            };
        };
  
        time.schedule(timetask, 1500, 2000);
    }
}
输出:
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
Stopping the task
The Purge value:0

方案二:

// Java code to illustrate purge()
  
import java.util.*;
  
public class Java_Timer_Demo {
  
    public static void main(String args[])
    {
  
        // Creating the timer task, timer
        Timer time = new Timer();
  
        TimerTask timetask = new TimerTask() {
            public void run()
            {
  
                for (int i = 1; i <= 5; i++) {
  
                    System.out.println("Working on the task");
  
                    if (i >= 2) {
  
                        System.out.println("Stopping the task");
                        time.cancel();
                    }
                }
  
                // Purging the timer
                System.out.println("The Purge value:"
                                   + time.purge());
            };
        };
  
        time.schedule(timetask, 1, 1000);
    }
}
输出:
Working on the task
Working on the task
Stopping the task
Working on the task
Stopping the task
Working on the task
Stopping the task
Working on the task
Stopping the task
The Purge value:0

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/Timer.html#purge–