Java中的DelayQueue迭代器(iterator())方法示例
iterator() 方法是用于在DelayQueue中返回迭代器以遍历所有元素的,这些元素可以是过期或未过期的。
语法:
public Iterator iterator ()
参数: 此方法不接受任何参数。
返回值: 此方法返回一个迭代器,用于在此DelayQueue中遍历元素。
以下程序演示了Java中的DelayQueue iterator()方法:
示例:
// Java程序演示DelayQueue迭代器(iterator())方法
import java.util.concurrent.*;
import java.util.*;
// DelayQueue中的DelayObject
// 必须实现Delayed和getDelay()和compareTo()方法
class DelayObject implements Delayed {
private String name;
private long time;
// DelayObject的构造函数
public DelayObject(String name, long delayTime)
{
this.name = name;
this.time = System.currentTimeMillis() + delayTime;
}
// 实现Delayed的getDelay()方法
@Override
public long getDelay(TimeUnit unit)
{
long diff = time - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
// 实现Delayed的compareTo()方法
@Override
public int compareTo(Delayed obj)
{
if (this.time < ((DelayObject)obj).time) {
return -1;
}
if (this.time > ((DelayObject)obj).time) {
return 1;
}
return 0;
}
// 实现Delayed的toString()方法
@Override
public String toString()
{
return "\n{" + " " + name + ", time=" + time + "}";
}
}
// Driver类
public class GFG {
public static void main(String[] args) throws InterruptedException
{
// 使用DelayQueue()构造函数创建DelayQueue对象
BlockingQueue DQ = new DelayQueue();
// 使用add()方法将数字添加到DelayQueue末尾
DQ.add(new DelayObject("A", 1));
DQ.add(new DelayObject("B", 2));
DQ.add(new DelayObject("C", 3));
DQ.add(new DelayObject("D", 4));
// 创建迭代器
Iterator val = DQ.iterator();
// 迭代DelayQueue后打印值
System.out.println("迭代器的值为: ");
while (val.hasNext()) {
System.out.println(val.next());
}
}
}
输出结果:
迭代器的值为:
{ A, time=1545818784540}
{ B, time=1545818784541}
{ C, time=1545818784542}
{ D, time=1545818784543}
极客教程