<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
定時器有三種表現形式:
JDK 提供了三種常用的定時器實現方式,分別為:
Timer
DelayedQueue
延遲佇列ScheduledThreadPoolExecutor
發現 eureka
中大量使用了 Timer
定時器:
Timer 是如何使用的,範例程式碼如下:
Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // 業務程式碼 } }, 5000, 5000); // 5s 後排程一個週期為 5s 的定時任務
TimerTask
是實現了 Runnable
介面的抽象類Timer
負責排程和執行 TimerTask
Timer
的內部構造,如下:
public class Timer { // 小根堆,run操作 O(1)、新增 O(logn)、cancel O(logn) private final TaskQueue queue = new TaskQueue(); // 建立另外執行緒,任務處理,會輪詢 queue private final TimerThread thread = new TimerThread(queue); public Timer(String name) { thread.setName(name); thread.start(); } }
Timer
它是存在不少設計缺陷的,所以並不推薦使用者使用:
Timer
是單執行緒模式,如果某個 TimerTask
執行時間很久,會影響其他任務的排程。Timer
的任務排程是基於系統絕對時間的,如果系統時間不正確,可能會出現問題。TimerTask
如果執行出現異常,Timer
並不會捕獲,會導致執行緒終止,其他任務永遠不會執行。特徵如下:
DelayedQueue
是 JDK 中一種可以延遲獲取物件的阻塞佇列,其內部是採用優先順序佇列 PriorityQueue
儲存物件DelayQueue
中的每個物件都必須實現 Delayed
介面,並重寫 compareTo
和 getDelay
方法DelayedQueue
的使用方法如下:
public class DelayQueueTest { public static void main(String[] args) throws Exception { BlockingQueue<SampleTask> delayQueue = new DelayQueue<>(); long now = System.currentTimeMillis(); delayQueue.put(new SampleTask(now + 1000)); delayQueue.put(new SampleTask(now + 2000)); delayQueue.put(new SampleTask(now + 3000)); for (int i = 0; i < 3; i++) { System.out.println(new Date(delayQueue.take().getTime())); } } static class SampleTask implements Delayed { long time; public SampleTask(long time) { this.time = time; } public long getTime() { return time; } @Override public int compareTo(Delayed o) { return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS)); } @Override public long getDelay(TimeUnit unit) { return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } } }
JDK
提供了功能更加豐富的 ScheduledThreadPoolExecutor
public class ScheduledExecutorServiceTest { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); executor.scheduleAtFixedRate(() -> System.out.println("Hello World"), 1000, 2000, TimeUnit.MILLISECONDS); // 1s 延遲後開始執行任務,每 2s 重複執行一次 } }
ScheduledThreadPoolExecutor
使用了阻塞佇列 DelayedWorkQueue
。
執行緒應該是最常見的實現方案,建立一個執行緒執行任務即可,舉例幾個不同的寫法,程式碼如下
4.1.使用thread + runnable
package com.yezi_tool.demo_basic.test; import org.springframework.stereotype.Component; import java.util.Date; @Component public class ThreadTest { private Integer count = 0; public ThreadTest() { test1(); } public void test1() { new Thread(() -> { while (count < 10) { System.out.println(new Date().toString() + ": " + count); count++; try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }
4.2.使用執行緒池 + runnable
package com.yezi_tool.demo_basic.test; import org.springframework.stereotype.Component; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Component public class ThreadTest { private static final ExecutorService threadPool = Executors.newFixedThreadPool(5);// 執行緒池 private Integer count = 0; public ThreadTest() { test2(); } public void test2() { threadPool.execute(() -> { while (count < 10) { System.out.println(new Date().toString() + ": " + count); count++; try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
以上就是Java 定時器的多種實現方式的詳細內容,更多關於Java 定時器的實現的資料請關注it145.com其它相關文章!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45