延迟队列
延迟队列一般应用于周期执行或延迟执行的线程池中,在写延迟队列之前,先写一个一般线程池中应用的阻塞队列,阻塞队列有个特点,当尝试去获取元素时,如果队列为空,则阻塞当前线程,直到有元素进入再次唤醒。
/**
* @author siiirius
* @since 2020-10-30 10:14
*/
public interface Queue<E> {
/**
* take an element from the queue and delete
*
* @return the element
*/
E take();
/**
* offer an element to the queue
*
* @param e the element
*/
void offer(E e);
}
为了简单,直接使用ArrayList作为容器,这里要注意,每个方法在释放锁的时候,都要检查是否需要唤醒正在等待的线程。
import java.util.ArrayList;
import java.util.List;
/**
* @author siiirius
* @since 2020-10-30 10:16
*/
public class BlockQueue<E> implements Queue<E> {
private List<E> container = new ArrayList<>();
private final Object lock = new Object();
@Override
public E take() {
synchronized (lock) {
try {
while (container.isEmpty()) {
try {
lock.wait();
} catch (InterruptedException e) {
return null;
}
}
return container.remove(