當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。