suchen

Heim  >  Fragen und Antworten  >  Hauptteil

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

<code>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();

        }

         

    }

 

}</code>

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

PHPzPHPz2808 Tage vor569

Antworte allen(1)Ich werde antworten

  • PHP中文网

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

    getDelay()始终返回1,所以永远不会expire。

    可以仔细研究一下DelayQueue的文档: https://docs.oracle.com/javas...

    Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS)
    method returns a value less than or equal to zero

    Antwort
    0
  • StornierenAntwort