解析Java中的定時(shí)器及使用定時(shí)器制作彈彈球游戲的示例
在我們編程過(guò)程中如果需要執(zhí)行一些簡(jiǎn)單的定時(shí)任務(wù),無(wú)須做復(fù)雜的控制,我們可以考慮使用JDK中的Timer定時(shí)任務(wù)來(lái)實(shí)現(xiàn)。下面LZ就其原理、實(shí)例以及Timer缺陷三個(gè)方面來(lái)解析java Timer定時(shí)器。
一、簡(jiǎn)介
在java中一個(gè)完整定時(shí)任務(wù)需要由Timer、TimerTask兩個(gè)類(lèi)來(lái)配合完成。 API中是這樣定義他們的,Timer:一種工具,線程用其安排以后在后臺(tái)線程中執(zhí)行的任務(wù)。可安排任務(wù)執(zhí)行一次,或者定期重復(fù)執(zhí)行。由TimerTask:Timer 安排為一次執(zhí)行或重復(fù)執(zhí)行的任務(wù)。我們可以這樣理解Timer是一種定時(shí)器工具,用來(lái)在一個(gè)后臺(tái)線程計(jì)劃執(zhí)行指定任務(wù),而TimerTask一個(gè)抽象類(lèi),它的子類(lèi)代表一個(gè)可以被Timer計(jì)劃的任務(wù)。
Timer類(lèi)
在工具類(lèi)Timer中,提供了四個(gè)構(gòu)造方法,每個(gè)構(gòu)造方法都啟動(dòng)了計(jì)時(shí)器線程,同時(shí)Timer類(lèi)可以保證多個(gè)線程可以共享單個(gè)Timer對(duì)象而無(wú)需進(jìn)行外部同步,所以Timer類(lèi)是線程安全的。但是由于每一個(gè)Timer對(duì)象對(duì)應(yīng)的是單個(gè)后臺(tái)線程,用于順序執(zhí)行所有的計(jì)時(shí)器任務(wù),一般情況下我們的線程任務(wù)執(zhí)行所消耗的時(shí)間應(yīng)該非常短,但是由于特殊情況導(dǎo)致某個(gè)定時(shí)器任務(wù)執(zhí)行的時(shí)間太長(zhǎng),那么他就會(huì)“獨(dú)占”計(jì)時(shí)器的任務(wù)執(zhí)行線程,其后的所有線程都必須等待它執(zhí)行完,這就會(huì)延遲后續(xù)任務(wù)的執(zhí)行,使這些任務(wù)堆積在一起,具體情況我們后面分析。
當(dāng)程序初始化完成Timer后,定時(shí)任務(wù)就會(huì)按照我們?cè)O(shè)定的時(shí)間去執(zhí)行,Timer提供了schedule方法,該方法有多中重載方式來(lái)適應(yīng)不同的情況,如下:
schedule(TimerTask task, Date time):安排在指定的時(shí)間執(zhí)行指定的任務(wù)。
schedule(TimerTask task, Date firstTime, long period) :安排指定的任務(wù)在指定的時(shí)間開(kāi)始進(jìn)行重復(fù)的固定延遲執(zhí)行。
schedule(TimerTask task, long delay) :安排在指定延遲后執(zhí)行指定的任務(wù)。
schedule(TimerTask task, long delay, long period) :安排指定的任務(wù)從指定的延遲后開(kāi)始進(jìn)行重復(fù)的固定延遲執(zhí)行。
同時(shí)也重載了scheduleAtFixedRate方法,scheduleAtFixedRate方法與schedule相同,只不過(guò)他們的側(cè)重點(diǎn)不同,區(qū)別后面分析。
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任務(wù)在指定的時(shí)間開(kāi)始進(jìn)行重復(fù)的固定速率執(zhí)行。
scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任務(wù)在指定的延遲后開(kāi)始進(jìn)行重復(fù)的固定速率執(zhí)行。
TimerTask
TimerTask類(lèi)是一個(gè)抽象類(lèi),由Timer 安排為一次執(zhí)行或重復(fù)執(zhí)行的任務(wù)。它有一個(gè)抽象方法run()方法,該方法用于執(zhí)行相應(yīng)計(jì)時(shí)器任務(wù)要執(zhí)行的操作。因此每一個(gè)具體的任務(wù)類(lèi)都必須繼承TimerTask,然后重寫(xiě)run()方法。
另外它還有兩個(gè)非抽象的方法:
boolean cancel():取消此計(jì)時(shí)器任務(wù)。
long scheduledExecutionTime():返回此任務(wù)最近實(shí)際執(zhí)行的安排執(zhí)行時(shí)間。
二、實(shí)例
2.1、指定延遲時(shí)間執(zhí)行定時(shí)任務(wù)
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!!!!"); } }
運(yùn)行結(jié)果:
首先打?。?/p>
timer begin....
3秒后打?。?/p>
Time's up!!!!
2.2、在指定時(shí)間執(zhí)行定時(shí)任務(wù)
public class TimerTest02 { Timer timer; public TimerTest02(){ Date time = getTime(); System.out.println("指定時(shí)間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("指定時(shí)間執(zhí)行線程任務(wù)..."); } }
當(dāng)時(shí)間到達(dá)11:39:00時(shí)就會(huì)執(zhí)行該線程任務(wù),當(dāng)然大于該時(shí)間也會(huì)執(zhí)行?。?zhí)行結(jié)果為:
指定時(shí)間time=Tue Jun 10 11:39:00 CST 2014 指定時(shí)間執(zhí)行線程任務(wù)...
2.3、在延遲指定時(shí)間后以指定的間隔時(shí)間循環(huán)執(zhí)行定時(shí)任務(wù)
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í)行該線程的時(shí)間為:" + date); } }
運(yùn)行結(jié)果:
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:47 CST 2014 本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:49 CST 2014 本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:51 CST 2014 本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:53 CST 2014 本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:55 CST 2014 本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:57 CST 2014 .................
對(duì)于這個(gè)線程任務(wù),如果我們不將該任務(wù)停止,他會(huì)一直運(yùn)行下去。
對(duì)于上面三個(gè)實(shí)例,LZ只是簡(jiǎn)單的演示了一下,同時(shí)也沒(méi)有講解scheduleAtFixedRate方法的例子,其實(shí)該方法與schedule方法一樣!
2.4、分析schedule和scheduleAtFixedRate
(1)schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)
對(duì)于這兩個(gè)方法而言,如果指定的計(jì)劃執(zhí)行時(shí)間scheduledExecutionTime<= systemCurrentTime,則task會(huì)被立即執(zhí)行。scheduledExecutionTime不會(huì)因?yàn)槟骋粋€(gè)task的過(guò)度執(zhí)行而改變。
(2)schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)
這兩個(gè)方法與上面兩個(gè)就有點(diǎn)兒不同的,前面提過(guò)Timer的計(jì)時(shí)器任務(wù)會(huì)因?yàn)榍耙粋€(gè)任務(wù)執(zhí)行時(shí)間較長(zhǎng)而延時(shí)。在這兩個(gè)方法中,每一次執(zhí)行的task的計(jì)劃時(shí)間會(huì)隨著前一個(gè)task的實(shí)際時(shí)間而發(fā)生改變,也就是scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime。也就是說(shuō)如果第n個(gè)task由于某種情況導(dǎo)致這次的執(zhí)行時(shí)間過(guò)程,最后導(dǎo)致systemCurrentTime>= scheduledExecutionTime(n+1),這是第n+1個(gè)task并不會(huì)因?yàn)榈綍r(shí)了而執(zhí)行,他會(huì)等待第n個(gè)task執(zhí)行完之后再執(zhí)行,那么這樣勢(shì)必會(huì)導(dǎo)致n+2個(gè)的執(zhí)行實(shí)現(xiàn)scheduledExecutionTime放生改變即scheduledExecutionTime(n+2) = realExecutionTime(n+1)+periodTime。所以這兩個(gè)方法更加注重保存間隔時(shí)間的穩(wěn)定。
(3)scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)
在前面也提過(guò)scheduleAtFixedRate與schedule方法的側(cè)重點(diǎn)不同,schedule方法側(cè)重保存間隔時(shí)間的穩(wěn)定,而scheduleAtFixedRate方法更加側(cè)重于保持執(zhí)行頻率的穩(wěn)定。為什么這么說(shuō),原因如下。在schedule方法中會(huì)因?yàn)榍耙粋€(gè)任務(wù)的延遲而導(dǎo)致其后面的定時(shí)任務(wù)延時(shí),而scheduleAtFixedRate方法則不會(huì),如果第n個(gè)task執(zhí)行時(shí)間過(guò)長(zhǎng)導(dǎo)致systemCurrentTime>= scheduledExecutionTime(n+1),則不會(huì)做任何等待他會(huì)立即執(zhí)行第n+1個(gè)task,所以scheduleAtFixedRate方法執(zhí)行時(shí)間的計(jì)算方法不同于schedule,而是scheduledExecutionTime(n)=firstExecuteTime +n*periodTime,該計(jì)算方法永遠(yuǎn)保持不變。所以scheduleAtFixedRate更加側(cè)重于保持執(zhí)行頻率的穩(wěn)定。
三、Timer的缺陷
3.1、Timer的缺陷
Timer計(jì)時(shí)器可以定時(shí)(指定時(shí)間執(zhí)行任務(wù))、延遲(延遲5秒執(zhí)行任務(wù))、周期性地執(zhí)行任務(wù)(每隔個(gè)1秒執(zhí)行任務(wù)),但是,Timer存在一些缺陷。首先Timer對(duì)調(diào)度的支持是基于絕對(duì)時(shí)間的,而不是相對(duì)時(shí)間,所以它對(duì)系統(tǒng)時(shí)間的改變非常敏感。其次Timer線程是不會(huì)捕獲異常的,如果TimerTask拋出的了未檢查異常則會(huì)導(dǎo)致Timer線程終止,同時(shí)Timer也不會(huì)重新恢復(fù)線程的執(zhí)行,他會(huì)錯(cuò)誤的認(rèn)為整個(gè)Timer線程都會(huì)取消。同時(shí),已經(jīng)被安排單尚未執(zhí)行的TimerTask也不會(huì)再執(zhí)行了,新的任務(wù)也不能被調(diào)度。故如果TimerTask拋出未檢查的異常,Timer將會(huì)產(chǎn)生無(wú)法預(yù)料的行為。
(1)Timer管理時(shí)間延遲缺陷
前面Timer在執(zhí)行定時(shí)任務(wù)時(shí)只會(huì)創(chuàng)建一個(gè)線程任務(wù),如果存在多個(gè)線程,若其中某個(gè)線程因?yàn)槟撤N原因而導(dǎo)致線程任務(wù)執(zhí)行時(shí)間過(guò)長(zhǎng),超過(guò)了兩個(gè)任務(wù)的間隔時(shí)間,會(huì)發(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應(yīng)該是在3s后執(zhí)行,其結(jié)果應(yīng)該是:
timerOne invoked ,the time:1001 timerOne invoked ,the time:3001
但是事與愿違,timerOne由于sleep(4000),休眠了4S,同時(shí)Timer內(nèi)部是一個(gè)線程,導(dǎo)致timeOne所需的時(shí)間超過(guò)了間隔時(shí)間,結(jié)果:
timerOne invoked ,the time:1000 timerOne invoked ,the time:5000
(2)Timer拋出異常缺陷
如果TimerTask拋出RuntimeException,Timer會(huì)終止所有任務(wù)的運(yùn)行。如下:
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("我會(huì)不會(huì)執(zhí)行呢??"); } }, 1000); } public static void main(String[] args) { TimerTest04 test = new TimerTest04(); test.timerOne(); test.timerTwo(); } }
運(yùn)行結(jié)果:timerOne拋出異常,導(dǎo)致timerTwo任務(wù)終止。
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)
對(duì)于Timer的缺陷,我們可以考慮 ScheduledThreadPoolExecutor 來(lái)替代。Timer是基于絕對(duì)時(shí)間的,對(duì)系統(tǒng)時(shí)間比較敏感,而ScheduledThreadPoolExecutor 則是基于相對(duì)時(shí)間;Timer是內(nèi)部是單一線程,而ScheduledThreadPoolExecutor內(nèi)部是個(gè)線程池,所以可以支持多個(gè)任務(wù)并發(fā)執(zhí)行。
3.2、用ScheduledExecutorService替代Timer
(1)解決問(wèn)題一:
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(); } }
運(yùn)行結(jié)果:
timerOne,the time:1003 timerTwo,the time:2005
(2)解決問(wèn)題二
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(); } }
運(yùn)行結(jié)果:
timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... timerTwo invoked ..... ........................
四、使用定時(shí)器實(shí)現(xiàn)彈彈球
模擬書(shū)上的一個(gè)例題做了一個(gè)彈彈球,是在畫(huà)布上的指定位置畫(huà)多個(gè)圓,經(jīng)過(guò)一段的延時(shí)后,在附近位置重新畫(huà)。使球看起來(lái)是動(dòng),通過(guò)JSpinner組件調(diào)節(jié)延時(shí),來(lái)控制彈彈球的移動(dòng)速度.
BallsCanvas.java
public class BallsCanvas extends Canvas implements ActionListener, FocusListener { private Ball balls[]; // 多個(gè)球 private Timer timer; private static class Ball { int x, y; // 坐標(biāo) Color color; // 顏色 boolean up, left; // 運(yùn)動(dòng)方向 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) { // 初始化顏色、延時(shí) 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)建定時(shí)器對(duì)象,delay指定延時(shí) timer.start(); } // 設(shè)置延時(shí) public void setDelay(int delay) { timer.setDelay(delay); } // 在canvas上面作畫(huà) public void paint(Graphics g) { for (int i = 0; i < balls.length; i++) { g.setColor(balls[i].color); // 設(shè)置顏色 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); // 畫(huà)指定直徑的圓 } } // 定時(shí)器定時(shí)執(zhí)行事件 @Override public void actionPerformed(ActionEvent e) { repaint(); // 重畫(huà) } // 獲得焦點(diǎn) @Override public void focusGained(FocusEvent e) { timer.stop(); // 定時(shí)器停止 } // 失去焦點(diǎn) @Override public void focusLost(FocusEvent e) { timer.restart(); // 定時(shí)器重啟動(dòng) } }
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值時(shí),單擊JSpinner的Up或者down按鈕時(shí),或者在JSpinner中按Enter鍵 ball.setDelay(Integer.parseInt("" + spinner.getValue())); } public static void main(String[] args) { new BallsJFrame(); } }
效果如下:
相關(guān)文章
分析Java并發(fā)編程之信號(hào)量Semaphore
Semaphore一般譯作信號(hào)量,它也是一種線程同步工具,主要用于多個(gè)線程對(duì)共享資源進(jìn)行并行操作的一種工具類(lèi)。它代表了一種許可的概念,是否允許多線程對(duì)同一資源進(jìn)行操作的許可,使用Semaphore可以控制并發(fā)訪問(wèn)資源的線程個(gè)數(shù)2021-06-06Java實(shí)現(xiàn)的mysql事務(wù)處理操作示例
這篇文章主要介紹了Java實(shí)現(xiàn)的mysql事務(wù)處理操作,結(jié)合實(shí)例形式較為詳細(xì)的分析了Java基于JDBC操作mysql數(shù)據(jù)庫(kù)實(shí)現(xiàn)事務(wù)處理的相關(guān)概念、操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-08-08圖文詳解如何將java編寫(xiě)的程序轉(zhuǎn)為exe文件
我們寫(xiě)的程序,要讓小伙伴打開(kāi)即用,可以將java程序生成可執(zhí)行文件,下面這篇文章主要給大家介紹了關(guān)于一步步教你如何將java編寫(xiě)的程序轉(zhuǎn)為exe文件的相關(guān)資料,需要的朋友可以參考下2023-01-01解決IDEA占用C盤(pán)空間過(guò)大的問(wèn)題
這篇文章主要介紹了解決IDEA占用C盤(pán)空間過(guò)大的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02SpringCloud Finchley Gateway 緩存請(qǐng)求Body和Form表單的實(shí)現(xiàn)
在接入Spring-Cloud-Gateway時(shí),可能有需求進(jìn)行緩存Json-Body數(shù)據(jù)或者Form-Urlencoded數(shù)據(jù)的情況。這篇文章主要介紹了SpringCloud Finchley Gateway 緩存請(qǐng)求Body和Form表單的實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2019-01-01springMvc注解之@ResponseBody和@RequestBody詳解
本篇文章主要介紹了springMvc注解之@ResponseBody和@RequestBody詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05JAVA實(shí)現(xiàn)往字符串中某位置加入一個(gè)字符串
這篇文章主要介紹了JAVA實(shí)現(xiàn)往字符串中某位置加入一個(gè)字符串,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08