您的位置:首页 > 产品设计 > UI/UE

DelayQueue

2014-01-08 23:06 405 查看
package collections;

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

/**
* 测试 DelayQueueTest
* User: zhangyong
* Date: 13-12-3
* Time: 下午10:29
* To change this template use File | Settings | File Templates.
*/
public class DelayQueueTest {

public static class DelayItem implements Delayed {

private final long time;

private final String name;

public DelayItem(String name, long timeout) {
this.name = name;
this.time = System.currentTimeMillis() + timeout;
}

public String getName() {
return name;
}

public long getDelay(TimeUnit unit) {
long d = unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
return d;
}

public int compareTo(Delayed other) {
DelayItem item = (DelayItem) other;
if (this.time > item.time) {
return 1;
} else {
return -1;
}
}

}

public static void main(String[] args) {
DelayQueue delayQueue = new DelayQueue();
DelayItem item3 = new DelayItem("30", 30 * 1000);
DelayItem item2 = new DelayItem("20s", 20 * 1000);
DelayItem item1 = new DelayItem("5s", 5 * 1000);

delayQueue.put(item3);
delayQueue.put(item2);
delayQueue.put(item1);

long startTime = System.currentTimeMillis();
for (; ; ) {
try {
DelayItem item = (DelayItem) delayQueue.take();
System.out.println(item.getName() + " 耗时:" + (System.currentTimeMillis() - startTime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: