cari

Rumah  >  Soal Jawab  >  teks badan

java - 为什么我的延迟队列取不出数据了?

我使用java的延迟队列来取数据,但是发现根本无法取出数据。

package com.test;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class SmsEntity implements Delayed {

    private final long WAIT_TIME = 10;

    private long startTime = System.currentTimeMillis();

    private String phone;

    public SmsEntity(String phone) {

        this.phone = phone;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    @Override
    public int compareTo(Delayed o) {

        SmsEntity entity = (SmsEntity) o;
        if (this.getStartTime() - entity.getStartTime() > 0) {
            return 1;
        }
        
        return -1;
    }

    @Override
    public long getDelay(TimeUnit unit) {
//        long waitTimeForGiveTimeUnit = unit.convert(WAIT_TIME, TimeUnit.MILLISECONDS);
//        long areadyLeftTime = unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
//                - unit.convert(startTime, TimeUnit.MILLISECONDS);
//        if (areadyLeftTime > waitTimeForGiveTimeUnit) {
//            return 0;
//        }
//        return unit.convert(waitTimeForGiveTimeUnit - areadyLeftTime, TimeUnit.MILLISECONDS);
        return  1;
    }

}


package com.test;

import java.util.concurrent.DelayQueue;

public class DelayQueueDemo {
    public static void main(String[] args)  {
        
        
        DelayQueue<SmsEntity>  queue=new DelayQueue<>();
        queue.put(new  SmsEntity("1"));
        try {
//            Thread.sleep(3000);
            queue.put(new  SmsEntity("2"));
            System.out.println(queue.take().getPhone());
            System.out.println(queue.take().getPhone());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }

}

结果是一直在阻塞。我想请教这是为什么,感觉自己调用的没有错啊

PHPzPHPz2804 hari yang lalu561

membalas semua(1)saya akan balas

  • PHP中文网

    PHP中文网2017-04-18 10:49:45

    getDelay() sentiasa mengembalikan 1, jadi ia tidak akan tamat tempoh.

    Anda boleh mengkaji dokumentasi DelayQueue dengan teliti: https://docs.oracle.com/javas...

    Tamat tempoh berlaku apabila kaedah getDelay(TimeUnit.NANOSECONDS)
    elemen mengembalikan nilai kurang daripada atau sama dengan sifar

    balas
    0
  • Batalbalas