BlockingQueue(阻塞队列)

BlockingQueue的核心方法有:

  • boolean add(E e),把e添加到BlockingQueue里。如果BlockingQueue可以容纳,则返回true,否则抛出异常。
  • boolean offer(E e),表示如果可能的话,将e加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false。
  • void put(E e),把e添加到BlockingQueue里,如果BlockQueue没有空间则调用此方法的线程被阻塞直到BlockingQueue里面有空间再继续。
  • E poll(long timeout, TimeUnit unit),取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null。
  • E take() ,取走BlockingQueue里排在首位的对象,若BlockingQueue为空,则调用此方法的线程被阻塞直到BlockingQueue有新的数据被加入。
  • int drainTo(Collection<? super E> c) 和 int drainTo(Collection<? super E> c, int maxElements) ,一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数),通过该方法,可以提升获取数据效率,不需要多次分批加锁或释放锁
  • 注意:BlockingQueue不接受null元素。试图add、put 或offer 一个null 元素时,某些实现会抛出NullPointerException。null被用作指示poll操作失败的警戒值

参考资料

results matching ""

    No results matching ""