Java 定時器的多種實現(xiàn)方式
一、前言
定時器有三種表現(xiàn)形式:
- 按固定周期定時執(zhí)行
- 延遲一定時間后執(zhí)行
- 指定某個時刻執(zhí)行
JDK 提供了三種常用的定時器實現(xiàn)方式,分別為:
TimerDelayedQueue延遲隊列ScheduledThreadPoolExecutor
(1)Timer
發(fā)現(xiàn) eureka 中大量使用了 Timer 定時器:
- Timer 屬于 JDK 比較早期版本的實現(xiàn),它可以實現(xiàn)固定周期的任務,以及延遲任務。
- Timer 會起動一個異步線程去執(zhí)行到期的任務,任務可以只被調(diào)度執(zhí)行一次,也可以周期性反復執(zhí)行多次。
Timer 是如何使用的,示例代碼如下:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// 業(yè)務代碼
}
}, 5000, 5000); // 5s 后調(diào)度一個周期為 5s 的定時任務
TimerTask是實現(xiàn)了Runnable接口的抽象類Timer負責調(diào)度和執(zhí)行TimerTask
Timer 的內(nèi)部構造,如下:
public class Timer {
// 小根堆,run操作 O(1)、新增 O(logn)、cancel O(logn)
private final TaskQueue queue = new TaskQueue();
// 創(chuàng)建另外線程,任務處理,會輪詢 queue
private final TimerThread thread = new TimerThread(queue);
public Timer(String name) {
thread.setName(name);
thread.start();
}
}
Timer 它是存在不少設計缺陷的,所以并不推薦用戶使用:
Timer是單線程模式,如果某個TimerTask執(zhí)行時間很久,會影響其他任務的調(diào)度。Timer的任務調(diào)度是基于系統(tǒng)絕對時間的,如果系統(tǒng)時間不正確,可能會出現(xiàn)問題。TimerTask如果執(zhí)行出現(xiàn)異常,Timer并不會捕獲,會導致線程終止,其他任務永遠不會執(zhí)行。
(2)DelayedQueue 延遲隊列
特征如下:
DelayedQueue是 JDK 中一種可以延遲獲取對象的阻塞隊列,其內(nèi)部是采用優(yōu)先級隊列PriorityQueue存儲對象DelayQueue中的每個對象都必須實現(xiàn)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);
}
}
}
(3)ScheduledThreadPoolExecutor
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 延遲后開始執(zhí)行任務,每 2s 重復執(zhí)行一次
}
}
ScheduledThreadPoolExecutor 使用了阻塞隊列 DelayedWorkQueue。
(4)ScheduledThreadPoolExecutor
線程應該是最常見的實現(xiàn)方案,創(chuàng)建一個線程執(zhí)行任務即可,舉例幾個不同的寫法,代碼如下
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 定時器的多種實現(xiàn)方式的詳細內(nèi)容,更多關于Java 定時器的實現(xiàn)的資料請關注腳本之家其它相關文章!
相關文章
spring-boot整合ehcache實現(xiàn)緩存機制的方法
spring-boot是一個快速的集成框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發(fā)過程。這篇文章主要介紹了spring-boot整合ehcache實現(xiàn)緩存機制,需要的朋友可以參考下2018-01-01
java調(diào)用webService接口的代碼實現(xiàn)
本文主要介紹了java調(diào)用webService接口的代碼實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
Java JDK與cglib動態(tài)代理有什么區(qū)別
這篇文章主要介紹了Java JDK動態(tài)代理和cglib動態(tài)代理的區(qū)別文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-03-03

