• java延时队列 示例



    /**
    * @desc: java 延时队列 思路:使用java.util.concurrent.DelayQueue队列,
    * 队列的元素需要实现Delayed接口的getDelay()和compareTo()两个方法
    * @author: 毛会懂
    * @create: 2022-02-08 17:20:00
    **/
    public class Test44Main {
    public static void main(String[] args) throws IOException {

    // 延迟队列
    DelayQueue<Obj> queue = new DelayQueue<>();

    // 线程1: 生产者 每隔2S产生一个对象
    CompletableFuture.runAsync(()->{
    System.out.println("启动生产者了");
    for(int i = 5; i < 30;i+=5){
    System.out.println("放入队列" + i);
    Obj temp = new Obj(i,TimeUnit.SECONDS,"name_" + i);
    queue.put(temp);
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });

    // 线程2: 消费者
    CompletableFuture.runAsync(() ->{
    System.out.println("启动消费者了");
    while (true){
    try {
    Obj take = queue.take();
    System.out.format("name={%s},time={%s},当前时间={%s} \n",take.name,take.time, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    System.out.println("主线程结束");
    System.in.read();
    }


    /**
    * @desc : 消费的对象需要实现Delayed接口的getDelay()和 compareTo()
    * @author : 毛会懂
    * @create: 2022/2/8 17:23:00
    **/
    public static class Obj implements Delayed {
    private long time;
    private String name;

    public Obj(long time,TimeUnit unit,String name){
    this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
    this.name = name;
    }

    @Override
    public long getDelay(TimeUnit unit) {
    // return time;
    return time - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {
    Obj obj = (Obj)o;
    long diff = this.time - obj.time ;
    if(diff > 0){
    return 1;
    }else if (diff < 0){
    return -1;
    }
    return 0;
    }

    @Override
    public String toString() {
    return "本对象的time=" + time + "name=" + name;
    }
    }

    }
  • 相关阅读:
    64位windows 7下配置TortoiseGit(转)
    linux中fork函数详解(转)
    Socket通信的Python实现
    Socket
    浅谈CSRF攻击方式(转)
    Burpsuite常用模块详解以及渗透测试上的运用
    大佬内网渗透技巧的独白(思路篇)
    CTFcrackTools-V3
    厂商要知道的漏洞防护措施
    如何运用kali-xplico网络取证分析?点开看看吧
  • 原文地址:https://www.cnblogs.com/maohuidong/p/15872269.html
Copyright © 2020-2023  润新知