java延时队列 示例

2022/2/8 20:43:34

本文主要是介绍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;
        }
    }

}


这篇关于java延时队列 示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程