解析Java中的定時器及使用定時器制作彈彈球游戲的示例
在我們編程過程中如果需要執(zhí)行一些簡單的定時任務,無須做復雜的控制,我們可以考慮使用JDK中的Timer定時任務來實現(xiàn)。下面LZ就其原理、實例以及Timer缺陷三個方面來解析java Timer定時器。
一、簡介
在java中一個完整定時任務需要由Timer、TimerTask兩個類來配合完成。 API中是這樣定義他們的,Timer:一種工具,線程用其安排以后在后臺線程中執(zhí)行的任務??砂才湃蝿請?zhí)行一次,或者定期重復執(zhí)行。由TimerTask:Timer 安排為一次執(zhí)行或重復執(zhí)行的任務。我們可以這樣理解Timer是一種定時器工具,用來在一個后臺線程計劃執(zhí)行指定任務,而TimerTask一個抽象類,它的子類代表一個可以被Timer計劃的任務。
Timer類
在工具類Timer中,提供了四個構造方法,每個構造方法都啟動了計時器線程,同時Timer類可以保證多個線程可以共享單個Timer對象而無需進行外部同步,所以Timer類是線程安全的。但是由于每一個Timer對象對應的是單個后臺線程,用于順序執(zhí)行所有的計時器任務,一般情況下我們的線程任務執(zhí)行所消耗的時間應該非常短,但是由于特殊情況導致某個定時器任務執(zhí)行的時間太長,那么他就會“獨占”計時器的任務執(zhí)行線程,其后的所有線程都必須等待它執(zhí)行完,這就會延遲后續(xù)任務的執(zhí)行,使這些任務堆積在一起,具體情況我們后面分析。
當程序初始化完成Timer后,定時任務就會按照我們設定的時間去執(zhí)行,Timer提供了schedule方法,該方法有多中重載方式來適應不同的情況,如下:
schedule(TimerTask task, Date time):安排在指定的時間執(zhí)行指定的任務。
schedule(TimerTask task, Date firstTime, long period) :安排指定的任務在指定的時間開始進行重復的固定延遲執(zhí)行。
schedule(TimerTask task, long delay) :安排在指定延遲后執(zhí)行指定的任務。
schedule(TimerTask task, long delay, long period) :安排指定的任務從指定的延遲后開始進行重復的固定延遲執(zhí)行。
同時也重載了scheduleAtFixedRate方法,scheduleAtFixedRate方法與schedule相同,只不過他們的側重點不同,區(qū)別后面分析。
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任務在指定的時間開始進行重復的固定速率執(zhí)行。
scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任務在指定的延遲后開始進行重復的固定速率執(zhí)行。
TimerTask
TimerTask類是一個抽象類,由Timer 安排為一次執(zhí)行或重復執(zhí)行的任務。它有一個抽象方法run()方法,該方法用于執(zhí)行相應計時器任務要執(zhí)行的操作。因此每一個具體的任務類都必須繼承TimerTask,然后重寫run()方法。
另外它還有兩個非抽象的方法:
boolean cancel():取消此計時器任務。
long scheduledExecutionTime():返回此任務最近實際執(zhí)行的安排執(zhí)行時間。
二、實例
2.1、指定延遲時間執(zhí)行定時任務
public class TimerTest01 {
Timer timer;
public TimerTest01(int time){
timer = new Timer();
timer.schedule(new TimerTaskTest01(), time * 1000);
}
public static void main(String[] args) {
System.out.println("timer begin....");
new TimerTest01(3);
}
}
public class TimerTaskTest01 extends TimerTask{
public void run() {
System.out.println("Time's up!!!!");
}
}
運行結果:
首先打?。?/p>
timer begin....
3秒后打?。?/p>
Time's up!!!!
2.2、在指定時間執(zhí)行定時任務
public class TimerTest02 {
Timer timer;
public TimerTest02(){
Date time = getTime();
System.out.println("指定時間time=" + time);
timer = new Timer();
timer.schedule(new TimerTaskTest02(), time);
}
public Date getTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 39);
calendar.set(Calendar.SECOND, 00);
Date time = calendar.getTime();
return time;
}
public static void main(String[] args) {
new TimerTest02();
}
}
public class TimerTaskTest02 extends TimerTask{
@Override
public void run() {
System.out.println("指定時間執(zhí)行線程任務...");
}
}
當時間到達11:39:00時就會執(zhí)行該線程任務,當然大于該時間也會執(zhí)行??!執(zhí)行結果為:
指定時間time=Tue Jun 10 11:39:00 CST 2014 指定時間執(zhí)行線程任務...
2.3、在延遲指定時間后以指定的間隔時間循環(huán)執(zhí)行定時任務
public class TimerTest03 {
Timer timer;
public TimerTest03(){
timer = new Timer();
timer.schedule(new TimerTaskTest03(), 1000, 2000);
}
public static void main(String[] args) {
new TimerTest03();
}
}
public class TimerTaskTest03 extends TimerTask{
@Override
public void run() {
Date date = new Date(this.scheduledExecutionTime());
System.out.println("本次執(zhí)行該線程的時間為:" + date);
}
}
運行結果:
本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:47 CST 2014 本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:49 CST 2014 本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:51 CST 2014 本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:53 CST 2014 本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:55 CST 2014 本次執(zhí)行該線程的時間為:Tue Jun 10 21:19:57 CST 2014 .................
對于這個線程任務,如果我們不將該任務停止,他會一直運行下去。
對于上面三個實例,LZ只是簡單的演示了一下,同時也沒有講解scheduleAtFixedRate方法的例子,其實該方法與schedule方法一樣!
2.4、分析schedule和scheduleAtFixedRate
(1)schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)
對于這兩個方法而言,如果指定的計劃執(zhí)行時間scheduledExecutionTime<= systemCurrentTime,則task會被立即執(zhí)行。scheduledExecutionTime不會因為某一個task的過度執(zhí)行而改變。
(2)schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)
這兩個方法與上面兩個就有點兒不同的,前面提過Timer的計時器任務會因為前一個任務執(zhí)行時間較長而延時。在這兩個方法中,每一次執(zhí)行的task的計劃時間會隨著前一個task的實際時間而發(fā)生改變,也就是scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime。也就是說如果第n個task由于某種情況導致這次的執(zhí)行時間過程,最后導致systemCurrentTime>= scheduledExecutionTime(n+1),這是第n+1個task并不會因為到時了而執(zhí)行,他會等待第n個task執(zhí)行完之后再執(zhí)行,那么這樣勢必會導致n+2個的執(zhí)行實現(xiàn)scheduledExecutionTime放生改變即scheduledExecutionTime(n+2) = realExecutionTime(n+1)+periodTime。所以這兩個方法更加注重保存間隔時間的穩(wěn)定。
(3)scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)
在前面也提過scheduleAtFixedRate與schedule方法的側重點不同,schedule方法側重保存間隔時間的穩(wěn)定,而scheduleAtFixedRate方法更加側重于保持執(zhí)行頻率的穩(wěn)定。為什么這么說,原因如下。在schedule方法中會因為前一個任務的延遲而導致其后面的定時任務延時,而scheduleAtFixedRate方法則不會,如果第n個task執(zhí)行時間過長導致systemCurrentTime>= scheduledExecutionTime(n+1),則不會做任何等待他會立即執(zhí)行第n+1個task,所以scheduleAtFixedRate方法執(zhí)行時間的計算方法不同于schedule,而是scheduledExecutionTime(n)=firstExecuteTime +n*periodTime,該計算方法永遠保持不變。所以scheduleAtFixedRate更加側重于保持執(zhí)行頻率的穩(wěn)定。
三、Timer的缺陷
3.1、Timer的缺陷
Timer計時器可以定時(指定時間執(zhí)行任務)、延遲(延遲5秒執(zhí)行任務)、周期性地執(zhí)行任務(每隔個1秒執(zhí)行任務),但是,Timer存在一些缺陷。首先Timer對調度的支持是基于絕對時間的,而不是相對時間,所以它對系統(tǒng)時間的改變非常敏感。其次Timer線程是不會捕獲異常的,如果TimerTask拋出的了未檢查異常則會導致Timer線程終止,同時Timer也不會重新恢復線程的執(zhí)行,他會錯誤的認為整個Timer線程都會取消。同時,已經(jīng)被安排單尚未執(zhí)行的TimerTask也不會再執(zhí)行了,新的任務也不能被調度。故如果TimerTask拋出未檢查的異常,Timer將會產生無法預料的行為。
(1)Timer管理時間延遲缺陷
前面Timer在執(zhí)行定時任務時只會創(chuàng)建一個線程任務,如果存在多個線程,若其中某個線程因為某種原因而導致線程任務執(zhí)行時間過長,超過了兩個任務的間隔時間,會發(fā)生一些缺陷:
public class TimerTest04 {
private Timer timer;
public long start;
public TimerTest04(){
this.timer = new Timer();
start = System.currentTimeMillis();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000); //線程休眠3000
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("timerOne invoked ,the time:" + (System.currentTimeMillis() - start));
}
}, 3000);
}
public static void main(String[] args) throws Exception {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
按照我們正常思路,timerTwo應該是在3s后執(zhí)行,其結果應該是:
timerOne invoked ,the time:1001 timerOne invoked ,the time:3001
但是事與愿違,timerOne由于sleep(4000),休眠了4S,同時Timer內部是一個線程,導致timeOne所需的時間超過了間隔時間,結果:
timerOne invoked ,the time:1000 timerOne invoked ,the time:5000
(2)Timer拋出異常缺陷
如果TimerTask拋出RuntimeException,Timer會終止所有任務的運行。如下:
public class TimerTest04 {
private Timer timer;
public TimerTest04(){
this.timer = new Timer();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
throw new RuntimeException();
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println("我會不會執(zhí)行呢??");
}
}, 1000);
}
public static void main(String[] args) {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
運行結果:timerOne拋出異常,導致timerTwo任務終止。
Exception in thread "Timer-0" java.lang.RuntimeException at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505)
對于Timer的缺陷,我們可以考慮 ScheduledThreadPoolExecutor 來替代。Timer是基于絕對時間的,對系統(tǒng)時間比較敏感,而ScheduledThreadPoolExecutor 則是基于相對時間;Timer是內部是單一線程,而ScheduledThreadPoolExecutor內部是個線程池,所以可以支持多個任務并發(fā)執(zhí)行。
3.2、用ScheduledExecutorService替代Timer
(1)解決問題一:
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println("timerOne,the time:" + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println("timerTwo,the time:" + (System.currentTimeMillis() - start));
}
},2000,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
運行結果:
timerOne,the time:1003 timerTwo,the time:2005
(2)解決問題二
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
throw new RuntimeException();
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("timerTwo invoked .....");
}
},2000,500,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
運行結果:
timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... ........................
四、使用定時器實現(xiàn)彈彈球
模擬書上的一個例題做了一個彈彈球,是在畫布上的指定位置畫多個圓,經(jīng)過一段的延時后,在附近位置重新畫。使球看起來是動,通過JSpinner組件調節(jié)延時,來控制彈彈球的移動速度.
BallsCanvas.java
public class BallsCanvas extends Canvas implements ActionListener,
FocusListener {
private Ball balls[]; // 多個球
private Timer timer;
private static class Ball {
int x, y; // 坐標
Color color; // 顏色
boolean up, left; // 運動方向
Ball(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
up = left = false;
}
}
public BallsCanvas(Color colors[], int delay) { // 初始化顏色、延時
this.balls = new Ball[colors.length];
for (int i = 0, x = 40; i < colors.length; i++, x += 40) {
balls[i] = new Ball(x, x, colors[i]);
}
this.addFocusListener(this);
timer = new Timer(delay, this); // 創(chuàng)建定時器對象,delay指定延時
timer.start();
}
// 設置延時
public void setDelay(int delay) {
timer.setDelay(delay);
}
// 在canvas上面作畫
public void paint(Graphics g) {
for (int i = 0; i < balls.length; i++) {
g.setColor(balls[i].color); // 設置顏色
balls[i].x = balls[i].left ? balls[i].x - 10 : balls[i].x + 10;
if (balls[i].x < 0 || balls[i].x >= this.getWidth()) { // 到水平方向更改方向
balls[i].left = !balls[i].left;
}
balls[i].y = balls[i].up ? balls[i].y - 10 : balls[i].y + 10;
if (balls[i].y < 0 || balls[i].y >= this.getHeight()) { // 到垂直方向更改方向
balls[i].up = !balls[i].up;
}
g.fillOval(balls[i].x, balls[i].y, 20, 20); // 畫指定直徑的圓
}
}
// 定時器定時執(zhí)行事件
@Override
public void actionPerformed(ActionEvent e) {
repaint(); // 重畫
}
// 獲得焦點
@Override
public void focusGained(FocusEvent e) {
timer.stop(); // 定時器停止
}
// 失去焦點
@Override
public void focusLost(FocusEvent e) {
timer.restart(); // 定時器重啟動
}
}
BallsJFrame.java
class BallsJFrame extends JFrame implements ChangeListener {
private BallsCanvas ball;
private JSpinner spinner;
public BallsJFrame() {
super("彈彈球");
this.setBounds(300, 200, 480, 360);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Color colors[] = { Color.red, Color.green, Color.blue,
Color.magenta, Color.cyan };
ball = new BallsCanvas(colors, 100);
this.getContentPane().add(ball);
JPanel panel = new JPanel();
this.getContentPane().add(panel, "South");
panel.add(new JLabel("Delay"));
spinner = new JSpinner();
spinner.setValue(100);
panel.add(spinner);
spinner.addChangeListener(this);
this.setVisible(true);
}
@Override
public void stateChanged(ChangeEvent e) {
// 修改JSpinner值時,單擊JSpinner的Up或者down按鈕時,或者在JSpinner中按Enter鍵
ball.setDelay(Integer.parseInt("" + spinner.getValue()));
}
public static void main(String[] args) {
new BallsJFrame();
}
}
效果如下:

相關文章
SpringCloud Finchley Gateway 緩存請求Body和Form表單的實現(xiàn)
在接入Spring-Cloud-Gateway時,可能有需求進行緩存Json-Body數(shù)據(jù)或者Form-Urlencoded數(shù)據(jù)的情況。這篇文章主要介紹了SpringCloud Finchley Gateway 緩存請求Body和Form表單的實現(xiàn),感興趣的小伙伴們可以參考一下2019-01-01
springMvc注解之@ResponseBody和@RequestBody詳解
本篇文章主要介紹了springMvc注解之@ResponseBody和@RequestBody詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05

