当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Timer purge()用法及代码示例


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

用法:

public int purge()

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


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

以下程序说明了Java中purge()方法的用法方式:

示例1:

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

示例2:

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



相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Timer purge() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。