LinkedBlockingQueue的使用
构造函数:
调用无参的构造方法来创建LinkedBlockingQueue的话,那么它的最大容量就是Integer.MAX_VALUE,我们把它称为“无界”,但是我们也可以指定最大容量,那么此队列又是一个“有界”队列了.
public LinkedBlockingQueue() {this(Integer.MAX_VALUE);}
public LinkedBlockingQueue(int capacity) {if (capacity <= 0) throw new IllegalArgumentException();this.capacity = capacity;last = head = new Node(null);}
public LinkedBlockingQueue(Collection<? extends E> c) {this(Integer.MAX_VALUE);//调用第二个构造方法,传入的capacity是Int的最大值,可以说 是一个无界队列。final ReentrantLock putLock = this.putLock;putLock.lock(); //开启排他锁try {int n = 0;//用于记录LinkedBlockingQueue的size//循环传入的c集合for (E e : c) {if (e == null)//如果enull,则抛出空指针异常throw new NullPointerException();if (n == capacity)//如果n=capacity,说明到了最大的容量,则抛出“Queue full”异常throw new IllegalStateException("Queue full");enqueue(new Node(e));//入队操作++n;//n自增}count.set(n);//设置count} finally {putLock.unlock();//释放排他锁}}
- a.向队列中推入元素
add方法在添加元素的时候,若超出了度列的长度会直接抛出异常
对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。
offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。
- b.从队列中弹出元素:
poll: 若队列为空,返回null。
remove:若队列为空,抛出NoSuchElementException异常。
take:若队列为空,发生阻塞,等待有元素。
peek方法,只是拿到头节点的值,但是不会移除该节点.
messageQueue的push和pop的方法
用于队列中元素的压入和弹出.
push方法通过调用LinkedBlockingQueue的put方法将数据压入队列.
pop方法通过调用LinkedBlockingQueue的poll方法将数据弹出队列.poll方法可以进行超时设置,
Predicate的使用
Predicate是个断言式接口其参数是
Predicate默认实现的三个重要方法and,or和negate对应了java的三个连接符号&&、||和!
判断参数是否符合test()方法体里面的判断,实现test方法.
/*** Evaluates this predicate on the given argument. ** @param t the input argument* @return {@code true} if the input argument matches the predicate,* otherwise {@code false}*/boolean test(T t);
