1、DelayQueue:
带有延迟时间的Queue,其中的元素只有当其指定了延迟时间到了,才能够从队列中获取元素。DelayQueue中的元素必须实现Delay接口,DelayQueue是一个没有大小限制的队列,应用场景很多,比如对缓存超时的数据进行移除、任务超时处理、空闲连接关闭等。
2、示例如下:
package net.oschina.tkj.mulitcoding.blockqueue.delayqueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; /** * 网民,放入延迟的时间队列 DelayQueue里面,元素要实现Delayed接口 * * @author Freedom * */ public class NetPerson implements Delayed { private final int id; // 身份证 private final String name; private final long endTime; public NetPerson(int id, String name, long endTime) { this.id = id; this.name = name; this.endTime = endTime; } public int getId() { return id; } public String getName() { return name; } public long getEndTime() { return endTime; } @Override public int compareTo(Delayed o) { NetPerson p = (NetPerson) o; return this.getDelay(TimeUnit.SECONDS) - p.getDelay(TimeUnit.SECONDS) > 0 ? 1 : -1; } @Override public long getDelay(TimeUnit unit) { return endTime - System.currentTimeMillis(); } @Override public String toString() { return "NetPerson [id=" + id + ", name=" + name + ", endTime=" + endTime + "]"; } }
package net.oschina.tkj.mulitcoding.blockqueue.delayqueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.DelayQueue; /** * 网吧类,为线程的任务类 * * @author Freedom * */ public class NetBar implements Runnable { // 定义一个阻塞的延迟的队列 private static BlockingQueue<NetPerson> queue = new DelayQueue<>(); // 登记用户上网的信息 public void registNetPerson(int id, String name, long money) { NetPerson person = new NetPerson(id, name, 1000 * money + System.currentTimeMillis()); System.out.println("用户:" + person + " 开始上网..."); queue.add(person); } /* * 用户下机 */ public void endPlay(NetPerson p) { System.out.println("用户:" + p + " 上机时间到了,下机..."); } @Override public void run() { NetPerson p = null; try { while (true) { p = queue.take(); endPlay(p); Thread.sleep(500); } } catch (InterruptedException e) { e.printStackTrace(); } } /** * 主函数 * * @param args */ public static void main(String[] args) { System.out.println("新的一天,网吧营业开始..."); NetBar bar = new NetBar(); Thread t1 = new Thread(bar); bar.registNetPerson(411, "张三", 10); bar.registNetPerson(342, "李四", 5); bar.registNetPerson(675, "王五", 3); t1.start(); } }