@大神愛吃茶java
java.util.Timer中的TimerTask類git
這個包java.util.Timer是Java中的一個實用工具類,用來調度未來某個時間執行的線程。github
TimerTask類的源碼:安全
public abstract class TimerTask implements Runnable { final Object lock = new Object(); int state = VIRGIN; static final int VIRGIN = 0; static final int SCHEDULED = 1; static final int EXECUTED = 2; static final int CANCELLED = 3; long nextExecutionTime; long period = 0; protected TimerTask() { } public abstract void run(); public boolean cancel() { synchronized(lock) { boolean result = (state == SCHEDULED); state = CANCELLED; return result; } } public long scheduledExecutionTime() { synchronized(lock) { return (period < 0 ? nextExecutionTime + period : nextExecutionTime - period); } } }
TimerTask是實現了Runnable接口的,使用時是使用的Timer類,Java Timer類是線程安全的,多個線程能夠共享一個Timer對象,而無需外部同步。使用時須要建立一個Timer對象。ide
使用實例:工具
import java.util.Timer; import java.util.TimerTask; public class Test extends TimerTask { private String name = ""; public Test(String name) { this.name = name; } @Override public void run() { System.out.println("execute:" + name); } public static void main(String[] args) { Timer timer = new Timer(); long delay1 = 1 * 1000; long period1 = 1000; // 從如今開始 1 秒鐘以後,每隔 1 秒鐘執行一次 job1 timer.schedule(new Test("test.."), delay1, period1); long delay2 = 2 * 1000; long period2 = 2000; // 從如今開始 2 秒鐘以後,每隔 2 秒鐘執行一次 job2 timer.schedule(new Test("testResult.."), delay2, period2); } }
輸出結果:this
Timer類包含幾個schedule()方法,用於安排任務在給定時間或延遲一段時間後運行一次:spa
public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); }