java 延迟队列怎么创建
时间: 2023-10-13 07:35:36 浏览: 82
你可以通过以下步骤创建 Java 延迟队列:
1. 导入延迟队列所需的类:
```java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
```
2. 创建 Delayed 接口的实现类,该类的对象将被存储在延迟队列中。例如:
```java
class DelayedTask implements Delayed {
private String name;
private long executeTime;
public DelayedTask(String name, long delay) {
this.name = name;
this.executeTime = System.currentTimeMillis() + delay;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = executeTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
long diff = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
return Long.compare(diff, 0);
}
@Override
public String toString() {
return "DelayedTask{" +
"name='" + name + '\'' +
", executeTime=" + executeTime +
'}';
}
}
```
3. 创建 DelayQueue 实例,将 Delayed 对象添加到队列中:
```java
DelayQueue<DelayedTask> delayQueue = new DelayQueue<>();
delayQueue.put(new DelayedTask("task1", 1000)); // 添加延迟 1s 的任务
delayQueue.put(new DelayedTask("task2", 2000)); // 添加延迟 2s 的任务
```
4. 使用 take() 方法获取延迟时间到的 Delayed 对象:
```java
while (true) {
DelayedTask task = delayQueue.take();
System.out.println(task);
}
```
以上就是创建 Java 延迟队列的基本步骤。你可以根据自己的需求进行修改和扩展。
阅读全文