定時器問題
定時器屬于基本的基礎組件,不管是用戶空間的程序開發,還是內核空間的程序開發,很多時候都需要有定時器作為基礎組件的支持。一個定時器的實現需要具備以下四種基本行為:添加定時器、取消定時器、定時器檢查、到期執行。
請設計一個定時器并實現以下三種基本行為,函數原型已給出,可使用任意編程語言設計數據結構及實現,并盡可能高效地支持大量定時器:
// 添加定時器:經過特定時間間隔后執行目標操作
// 輸入 1:Interval 定時器時間,單位ms
// 輸入 2:ExpiryAction 目標操作
// 返回:定時器 Id
StartTimer(Interval, ExpiryAction) -> TimerId
// 取消定時器
// 輸入:定時器 Id
StopTimer(TimerId)
// 定時器檢查
// 系統每隔 10ms 會調用一次該函數
PerTickBookkeeping()
話不多說,直接上代碼:
1)Timer.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
import java.util.ArrayList; public class Timer { private long interval; // 定時器時間,單位 ms private String expiryAction; // 目標操作 private int timerId; // 定時器Id private long waitTime; // 定時器等待時間 // 構造函數 public Timer(){ this .waitTime = 0 ; } // 添加定時器 public int StartTimer( long interval, String expiryAction, int id){ this .interval = interval; this .expiryAction = expiryAction; this .timerId = id; return timerId; } // 取消定時器 public void StopTimer( int timerId, ArrayList<Timer> timer){ timer.remove(timerId); } // 定時器檢查 public void PerTickBookkeeping(){ if ( this .interval > this .waitTime) this .waitTime += 10 ; else { System.out.println( "定時器" + this .timerId+ ":" + this .expiryAction); this .waitTime = 0 ; } } public long getInterval() { return interval; } public void setInterval( long interval) { this .interval = interval; } public String getExpiryAction() { return expiryAction; } public void setExpiryAction(String expiryAction) { this .expiryAction = expiryAction; } public int getTimerId() { return timerId; } public void setTimerId( int timerId) { this .timerId = timerId; } public long getWaitTime() { return waitTime; } public void setWaitTime( long waitTime) { this .waitTime = waitTime; } } |
2)DoTimer.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import java.util.ArrayList; import java.util.Iterator; public class DoTimer extends Thread { private static ArrayList<Timer> timerList; public static void main(String[] args){ timerList = new ArrayList<Timer>(); Timer timer1 = new Timer(); timer1.StartTimer( 3000 , "我是第一個定時器,等待3秒" , 0 ); Timer timer2 = new Timer(); timer2.StartTimer( 4000 , "我是第二個定時器,等待4秒" , 1 ); timerList.add(timer1); timerList.add(timer2); //public void run(){} new Thread(){ @Override public void run() { while ( true ){ Iterator<Timer> it = timerList.iterator(); while (it.hasNext()){ it.next().PerTickBookkeeping(); } try { sleep( 10 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); timer1.StopTimer(timer1.getTimerId(), timerList); } } |
希望本篇文章可以幫助到您
原文鏈接:http://www.cnblogs.com/xiaoli-home/p/6683772.html