一步一步學多線程-Timer,多線程-timer

來源:互聯網
上載者:User

一步一步學多線程-Timer,多線程-timer

  在執行定時任務的時候可以用Timer來實現,現在小編對學到的進行一次總結,先來看一個demo

 1 public class TimerTest { 2  3     public static void main(String[] args) throws ParseException { 4         Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-08-17 11:18:00"); 5         new Timer().schedule(new TimerTask() { 6             @Override 7             public void run() { 8                 System.out.println(new Date().getSeconds()+"  執行"); 9             }10         }, date);11     }12 }

  這段代碼的意思是,先建一個Timer,Timer開始執行的時間是” 2017-08-17 11:18:00”。

Timer重複執行

  上述代碼Timer只會執行一次,如果我們想讓定時任務每隔一段時間就執行呢?此時可以用Timer提供的schedule方法的另一個重載 public void schedule(TimerTask task, long delay, long period)。意思是Timer在delay的時候開始執行,每隔period時間長度執行一次。

 1 public class TimerTest { 2  3     public static void main(String[] args) throws ParseException { 4         Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-08-17 11:18:00"); 5         new Timer().schedule(new TimerTask() { 6             @Override 7             public void run() { 8                 System.out.println(new Date().getSeconds()+"  執行"); 9             }10         }, date,1000);11     }12 }
執行結果

  37  執行

  38  執行

  39  執行

  40  執行

  ……

Timer執行延時

  在執行TimerTask的時候可能會出現線程執行時間過長的情況,超過了Timer的等待時間。此時會是什麼情況呢?

  

 1 public class TimerTest { 2  3     public static void main(String[] args) throws ParseException { 4         Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-08-17 11:18:00"); 5         new Timer().schedule(new TimerTask() { 6             @Override 7             public void run() { 8                 System.out.println(new Date().getSeconds()+"  開始執行"); 9                 try {10                     Thread.sleep(2000);11                     System.out.println(new Date().getSeconds()+"  執行結束");12                 } catch (InterruptedException e) {13                     e.printStackTrace();14                 }15             }16         }, date,1000);17     }18 }
看執行結果

  0  開始執行

  2  執行結束

  2  開始執行

  4  執行結束

  4  開始執行

  6  執行結束

  6  開始執行

  8  執行結束

  8  開始執行

scheduleAtFixedRate

  使用schedule方法執行Timer任務,如果開始的時間是在目前時間之前,Timer並不會對之前沒有執行的任務進行補充執行。也就是延時之後,那麼Timer就從目前時間開始接著按照間隔時間執行。但是有時候我們的需求更加關注的執行的頻率,需要把因為延時而導致沒有執行的任務補充回來,此時就需要用到scheduleAtFiexdRate。

 1 public class TimerTest { 2  3     public static void main(String[] args) throws ParseException { 4         final Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-08-17 11:52:00"); 5         new Timer().scheduleAtFixedRate(new TimerTask() { 6             @Override 7             public void run() { 8                 System.out.println(date); 9                 System.out.println(new Date().getSeconds() + "  開始執行");10                 System.out.println("執行了");11                 System.out.println(new Date().getSeconds() + "  執行結束");12 13             }14         }, date, 10000);15     }16 }
執行結果 

  39  開始執行

  執行了

  39  執行結束

  Thu Aug 17 11:52:00 CST 2017

  39  開始執行

  執行了

  39  執行結束

  Thu Aug 17 11:52:00 CST 2017

  40  開始執行

  執行了

  40  執行結束

 

  通過執行結果可以看出來,scheduleAtFixedRate上來就先將缺失的執行補上,然後再開始按照間隔時間一次一次執行。

將Timer設定成守護線程
 1 public class TimerTest { 2  3     public static void main(String[] args) throws ParseException { 4         final Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-08-17 11:52:00"); 5         Timer timer=new Timer(); 6         TimerTask timerTask= new TimerTask() { 7             @Override 8             public void run() { 9                 System.out.println(date);10                 System.out.println(new Date().getSeconds() + "  開始執行");11                 System.out.println("執行了");12                 System.out.println(new Date().getSeconds() + "  執行結束");13 14             }15         };16         timer.schedule(timerTask, date);17     }18 }

 

  在執行完代碼之後,程式仍然在運行。看Timer.class的原始碼可以發現Timer是建立了一個新的線程,而持續跟蹤代碼發現,新的線程進行了一個while(true)迴圈,再其中進入了等待狀態。

1 public Timer(String name) {2     thread.setName(name);3     thread.start();4 }
解決辦法

  將Timer設定成守護線程,Timer有個建構函式。

1 public Timer(boolean isDaemon) {2     this("Timer-" + serialNumber(), isDaemon);3 }

  所以我們在將new Timer()改為new Timer(true)即可。

TimerTask和Timer的cancel方法 

  TimerTask的cancel方法是關閉這個任務,Timer的cancel方法是關閉整個Timer。

  Timer的執行實際上是啟動了一個線程然後,線程中維護了一個隊列,然後把TimerTask放入隊列中。TimerTask的cancel方法就是將自身從任務隊列中移除。Timer的cancel方法,是將隊列中的任務全部清空。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.