DelayQueue是Java中基于延遲時(shí)間排序的無(wú)界阻塞隊(duì)列,用于實(shí)現(xiàn)延遲任務(wù)調(diào)度。1. Delayed接口需實(shí)現(xiàn)getDelay()和compareTo()方法,確保任務(wù)按延遲時(shí)間有序取出。2. 自定義DelayTask類實(shí)現(xiàn)Delayed接口,封裝任務(wù)ID和執(zhí)行時(shí)間戳。3. 使用DelayQueue存儲(chǔ)任務(wù),通過(guò)單獨(dú)消費(fèi)者線程調(diào)用take()獲取到期任務(wù)并執(zhí)行。4. 注意線程安全、單消費(fèi)者模式、延遲精度、異常處理及優(yōu)雅關(guān)閉。適用于輕量級(jí)場(chǎng)景,如緩存清理、延時(shí)消息,無(wú)需引入復(fù)雜調(diào)度框架。
在Java中,DelayQueue 是一個(gè)無(wú)界阻塞隊(duì)列,用于存放實(shí)現(xiàn)了 Delayed 接口的對(duì)象。只有當(dāng)對(duì)象的延遲時(shí)間到期后,才能從隊(duì)列中獲取到它。這個(gè)特性非常適合實(shí)現(xiàn)延遲任務(wù)調(diào)度,比如定時(shí)清理緩存、延時(shí)發(fā)送消息等場(chǎng)景。
Delayed 接口要求實(shí)現(xiàn)兩個(gè)方法:
只有當(dāng) getDelay() 返回值小于等于0時(shí),元素才會(huì)被取出。
創(chuàng)建一個(gè)類實(shí)現(xiàn) Delayed 接口,表示具體的延遲任務(wù)。例如:
立即學(xué)習(xí)“Java免費(fèi)學(xué)習(xí)筆記(深入)”;
import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; <p>public class DelayTask implements Delayed { private String taskId; private long executeTime; // 執(zhí)行時(shí)間戳(毫秒)</p><pre class='brush:java;toolbar:false;'>public DelayTask(String taskId, long delayInMs) { this.taskId = taskId; this.executeTime = System.currentTimeMillis() + delayInMs; } @Override public long getDelay(TimeUnit unit) { long diff = executeTime - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed other) { return Long.compare(this.executeTime, ((DelayTask) other).executeTime); } public String getTaskId() { return taskId; }
}
啟動(dòng)一個(gè)消費(fèi)者線程,不斷從隊(duì)列中獲取到期的任務(wù)并執(zhí)行:
import java.util.concurrent.*; <p>public class DelayTaskScheduler { private final DelayQueue<DelayTask> queue = new DelayQueue<>();</p><pre class='brush:java;toolbar:false;'>public void addTask(DelayTask task) { queue.put(task); } public void start() { new Thread(() -> { try { while (!Thread.interrupted()) { DelayTask task = queue.take(); // 阻塞直到任務(wù)到期 System.out.println("執(zhí)行任務(wù): " + task.getTaskId()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); } public static void main(String[] args) { DelayTaskScheduler scheduler = new DelayTaskScheduler(); scheduler.start(); // 添加幾個(gè)延遲任務(wù) scheduler.addTask(new DelayTask("任務(wù)1", 2000)); scheduler.addTask(new DelayTask("任務(wù)2", 5000)); scheduler.addTask(new DelayTask("任務(wù)3", 3000)); System.out.println("所有任務(wù)已提交"); }
}
輸出結(jié)果會(huì)是:
所有任務(wù)已提交 執(zhí)行任務(wù): 任務(wù)1 執(zhí)行任務(wù): 任務(wù)3 執(zhí)行任務(wù): 任務(wù)2基本上就這些。DelayQueue 簡(jiǎn)單高效,適用于輕量級(jí)延遲任務(wù)場(chǎng)景,不需要引入 Quartz 或 ScheduledExecutorService 的復(fù)雜性。
以上就是在Java中如何使用DelayQueue實(shí)現(xiàn)延遲任務(wù)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺(tái)速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊(cè)表數(shù)據(jù)和不必要的后臺(tái)進(jìn)程會(huì)占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)