本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.DelayQueue类
publicclassDelayQueue<EextendsDelayed>extendsAbstractQueue<E> implementsBlockingQueue<E>
DelayQueue 继承AbstractQueue抽象类,实现BlockingQueue接口,元素必须实现实现Delayed接口。
2.take()出队流程
(1)加锁;
(2)判断堆顶元素是否为空,为空的话直接阻塞等待;
(3)判断堆顶元素是否到期,到期了直接poll()出元素;
(4)没到期,再判断前面是否有其它线程在等待,有则直接等待;
(5)前面没有其它线程在等待,则把自己当作第一个线程等待delay时间后唤醒,再尝试获取元素;
(6)获取到元素之后再唤醒下一个等待的线程;
(7)解锁;
3.take出队实例
publicEtake()throwsInterruptedException{
finalReentrantLocklock=this.lock;
lock.lockInterruptibly();
try{
for(;;){
Efirst=q.peek();
if(first==null)
available.await();
else{
longdelay=first.getDelay(NANOSECONDS);
if(delay<=0)
returnq.poll();
first=null;//don'tretainrefwhilewaiting
if(leader!=null)
available.await();
else{
ThreadthisThread=Thread.currentThread();
leader=thisThread;
try{
available.awaitNanos(delay);
}finally{
if(leader==thisThread)
leader=null;
}
}
}
}
}finally{
if(leader==null&&q.peek()!=null)
available.signal();
lock.unlock();
}
}
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    















































 
        

暂无评论内容