LinkedBlockingQueue的使用

构造函数:
调用无参的构造方法来创建LinkedBlockingQueue的话,那么它的最大容量就是Integer.MAX_VALUE,我们把它称为“无界”,但是我们也可以指定最大容量,那么此队列又是一个“有界”队列了.

  1. public LinkedBlockingQueue() {
  2. this(Integer.MAX_VALUE);
  3. }
  1. public LinkedBlockingQueue(int capacity) {
  2. if (capacity <= 0) throw new IllegalArgumentException();
  3. this.capacity = capacity;
  4. last = head = new Node(null);
  5. }
  1. public LinkedBlockingQueue(Collection<? extends E> c) {
  2. this(Integer.MAX_VALUE);//调用第二个构造方法,传入的capacity是Int的最大值,可以说 是一个无界队列。
  3. final ReentrantLock putLock = this.putLock;
  4. putLock.lock(); //开启排他锁
  5. try {
  6. int n = 0;//用于记录LinkedBlockingQueue的size
  7. //循环传入的c集合
  8. for (E e : c) {
  9. if (e == null)//如果enull,则抛出空指针异常
  10. throw new NullPointerException();
  11. if (n == capacity)//如果n=capacity,说明到了最大的容量,则抛出“Queue full”异常
  12. throw new IllegalStateException("Queue full");
  13. enqueue(new Node(e));//入队操作
  14. ++n;//n自增
  15. }
  16. count.set(n);//设置count
  17. } finally {
  18. putLock.unlock();//释放排他锁
  19. }
  20. }
  • a.向队列中推入元素

add方法在添加元素的时候,若超出了度列的长度会直接抛出异常
对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。
offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。

  • b.从队列中弹出元素:

poll: 若队列为空,返回null。
remove:若队列为空,抛出NoSuchElementException异常。
take:若队列为空,发生阻塞,等待有元素。
peek方法,只是拿到头节点的值,但是不会移除该节点.

messageQueue的push和pop的方法

用于队列中元素的压入和弹出.
push方法通过调用LinkedBlockingQueue的put方法将数据压入队列.
pop方法通过调用LinkedBlockingQueue的poll方法将数据弹出队列.poll方法可以进行超时设置,

Predicate的使用

Predicate是个断言式接口其参数是,也就是给一个参数T,返回boolean类型的结果.
Predicate默认实现的三个重要方法and,or和negate对应了java的三个连接符号&&、||和!
判断参数是否符合test()方法体里面的判断,实现test方法.

  1. /**
  2. * Evaluates this predicate on the given argument. *
  3. * @param t the input argument
  4. * @return {@code true} if the input argument matches the predicate,
  5. * otherwise {@code false}
  6. */
  7. boolean test(T t);