-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestDelayQueue.java
113 lines (96 loc) · 2.78 KB
/
TestDelayQueue.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.cjs.block_queue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class TestDelayQueue {
public static void main(String[] args) throws InterruptedException {
DelayQueue<MovieTiket> delayQueue = new DelayQueue<>();
MovieTiket ticket = new MovieTiket("电影票0", 10000);
delayQueue.put(ticket);
MovieTiket ticket2 = new MovieTiket("电影票1", 5000);
delayQueue.put(ticket2);
MovieTiket tiket3 = new MovieTiket("电影票2", 8000);
delayQueue.put(tiket3);
System.out.println("message:--->入队完毕");
while (delayQueue.size() > 0) {
try {
ticket = delayQueue.take();
System.out.println("电影票出队:" + ticket.getMsg() + ":::" + ticket);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MovieTiket implements Delayed {
//延迟时间
private final long delay;
//到期时间
private final long expire;
//数据
private final String msg;
//创建时间
private final long now;
public long getDelay() {
return delay;
}
public long getExpire() {
return expire;
}
public String getMsg() {
return msg;
}
public long getNow() {
return now;
}
/**
* @param msg 消息
* @param delay 延期时间
*/
public MovieTiket(String msg, long delay) {
this.delay = delay;
this.msg = msg;
now = System.currentTimeMillis();
expire = now + delay; //到期时间 = 当前时间+延迟时间
}
/**
* @param msg
*/
public MovieTiket(String msg) {
this(msg, 1000);
}
public MovieTiket() {
this(null, 1000);
}
/**
* 获得延迟时间 用过期时间-当前时间,时间单位毫秒
*
* @param unit
* @return
*/
public long getDelay(TimeUnit unit) {
return unit.convert(this.expire
- System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
/**
* 用于延迟队列内部比较排序 当前时间的延迟时间 - 比较对象的延迟时间
* 越早过期的时间在队列中越靠前
*
* @param delayed
* @return
*/
public int compareTo(Delayed delayed) {
return (int) (this.getDelay(TimeUnit.MILLISECONDS)
- delayed.getDelay(TimeUnit.MILLISECONDS));
}
@Override
public String toString() {
return "MovieTiket{" +
"delay=" + delay +
", expireAt=" + expire +
", msg='" + msg + '\'' +
", now=" + now +
", 已经过去=" + (expire - now) +
'}';
}
}