Delay延迟队列
1.BIO、NIO、AIO的区别2.Controller是线程安全吗3.为什么多线程下会有线程安全问题4.volatile为什么没有原子性?5.JVM的四种内存屏障6.synchronized关键字原理7.synchronized 锁升级 锁降级8.自旋锁、阻塞锁、可重入锁使用解析9.线程间实现通信的几种方式10.ThreadPoolExecutor线程池参数设置技巧11.关于线程同步(7种同步方式)12.ThreadLocal可能引起的内存泄露13.乐观锁的一种实现方式——CAS14.AtomicInteger源码解析15.ReentrantLock源码解析1--获得非公平锁与公平锁lock()16.ReentrantLock源码解析2--释放锁unlock()17.ReentrantLock源码解析3--优先响应中断的lockInterruptibly18.ReentrantLock总结19.ArrayBlockingQueue源码解析20.LinkedBlockingQueue源码解析21.Timer / TimerTask 源码解析
22.Delay延迟队列
DelayEvent.java
public class DelayEvent2 implements Delayed { //到期时间 private Date startDate; public DelayEvent2(Date startDate) { this.startDate = startDate; } public int compareTo(Delayed o){ long result = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } /** * 返回与此对象相关的剩余延迟时间,以给定的时间单位表示 */ public long getDelay(TimeUnit unit){ Date now = new Date(); long diff = startDate.getTime() - now.getTime(); return unit.convert(diff, TimeUnit.MILLISECONDS); } }
DelayTask.java
/** * 任务任务 * 作用:添加100个新DelayEvent到DelayQueue队列中 */ public class DelayTask2 implements Runnable{ //添加时间 private int id; //队列 private DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>(); public DelayTask2(int id, DelayQueue<DelayEvent2> dq) { this.id = id; this.dq = dq; } public void run() { //旧Date Date date = new Date(); //新Date Date delay = new Date(); delay.setTime(date.getTime() + id * 1000); System.out.println("Thread 时间+:" + id + " 新Date:" + delay); //将100个DelayEvent放入DelayQueue for(int i = 0;i < 100;i++){ DelayEvent2 de = new DelayEvent2(delay); dq.add(de); } } }
DelayDequeueMain.java
public class DelayDequeMain2 { public static void main(String[] args) throws Exception{ DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>(); Thread threads[] = new Thread[5]; for(int i = 0;i < threads.length;i++){ DelayTask2 task = new DelayTask2(i+1,dq); threads[i] = new Thread(task); } for(int i = 0;i < threads.length;i++){ threads[i].start(); } for(int i = 0;i < threads.length;i++){ threads[i].join(); } do{ int counter = 0; DelayEvent2 delayEvent2; do{ delayEvent2 = dq.poll(); if(delayEvent2 != null){ counter++; } }while(delayEvent2!=null); System.out.println("At " + new Date() + " you have read " + counter + " event"); TimeUnit.MILLISECONDS.sleep(500); }while(dq.size()>0); } }
合集:
并发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了