三、当你点了菜,你还需要等待的DelayQueue
在现实中,我们点了菜之后呢,往往还需要等待厨师做的一个过程。厨师把未加工的菜放到队列里面任你挑选,你挑选了之后不能立刻拿走,他还需要帮你加工,联想自助餐厅拿生牛排的时候,你拿了牛排得给厨师他帮你烹饪。在多线程中延时队列DelayQueue体现了就是这样一个场景,每一个资源呢都有一个延时期限,假设当前资源已经排到队头,准备出列,但是此时不能出列,需要经过一段延时期之后才能出列。下面来根据代码理解一下这个类体现的作用。
public class DelayQueueTest {
public static class Fen implements Delayed{
private String name;
private int wtime;
private Date buildTime;
public Fen(int wtime,String name){
this.name="需要用"+wtime+"秒做的"+name;
this.wtime=wtime;
this.buildTime = new Date();
}
public String getName(){
return name;
}
public Date getBuildTime(){
return this.buildTime;
}
@Override
public int compareTo(Delayed fen) {
Fen f = (Fen)fen;
return this.buildTime.compareTo(f.getBuildTime());
}
@Override
public long getDelay(TimeUnit unit) {
//队列选中该对象进行消耗时,会调用一次该方法来确定返回时间
//然后等时间结束后会再调用一次该方法进行确认,如果是小于等于0,那么就返回消耗对象
//该方法返回的long 是经过unit转换之后的 (结束时间-当前时间)的值,即返回时间差,需要是动态变化
long gap = buildTime.getTime()+TimeUnit.SECONDS.toMillis(wtime)-System.currentTimeMillis();
if(gap!=0L){
System.out.println("烹饪中...");
System.out.println(gap);
}
return unit.convert(buildTime.getTime()+TimeUnit.SECONDS.toMillis(wtime)-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
}
}
public static void main(String[] args){
DelayQueue<Fen> valve = new DelayQueue<Fen>();
Thread fenOffer = new Thread(new Runnable() {
@Override
public void run() {
int random = new Random().nextInt(7);
Fen fen = new Fen(random,"肠粉");
System.out.println("把"+fen.getName()+"放入队列");
valve.put(fen);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread fenConsumer = new Thread(new Runnable() {
@Override
public void run() {
Fen f=null;
try {
f = valve.take();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("吃了"+f.getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
fenOffer.start();
fenConsumer.start();
}
}
结果:
把需要用1秒做的肠粉放入队列
烹饪中...
1000
烹饪中...
-14
吃了需要用1秒做的肠粉
上述代码体现了就是一个延时等待的过程,他要求每一个资源都需要实现Delayed接口,该接口中实现两个方法。
long getDelay(TimeUnit unit)
int compareTo(T o)
第二个效果同优先级阻塞队列,不谈
主要谈第一个方法,搞了一个下午才明天他实现的机制。
当资源到队头的时候呢,首先队列会调用一下getDelay方法,此时方法返回一个正数代表需要延迟的时间。队列就会把这个时间呢默默的记在心里,然后等到时间一到,注意:会再次调用该方法判断是否变成了负数!因为这个方法就是要一个动态时间差的效果,他需要每次调用该方法时都知道现在离结束时间还有多久,所以大家一定要远离这个坑,我查了百度,api说的都是很浅,都是靠自己实践菜出了真知,与大家分享!