ArrayBlockingQueue阻塞队列

ArrayBlockingQueue阻塞队列**ArrayBlockingQueue是****一个由数组支持的有界阻塞队列。此队列按 FIFO原则对元素进行排序。

大家好,欢迎来到IT知识分享网。

ArrayBlockingQueue是一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列检索操作则是从队列头部开始获得元素。

/** 数组存储 */

private final E[] items;

/** 队尾下标 */

private int takeIndex;

/** 队列头下标 */

private int putIndex;

/** 数组的长度 */

private int count;

  • offer()方法,将元素插入到队列,如果队列满了就返回false。

public boolean offer(E e) {

if (e == null) throw new NullPointerException();

final ReentrantLock lock = this.lock;

//如果没有被其它线程持有,便获取。否则等待

lock.lock();

try {

if (count == items.length)

return false;

else {

insert(e);

return true;

}

} finally {

lock.unlock();

}

}

  • put()方法,将指定的元素插入此队列的尾部,如果该队列已满,则等待可用的空间。

public void put(E e) throws InterruptedException {

if (e == null) throw new NullPointerException();

final E[] items = this.items;

final ReentrantLock lock = this.lock;

/**线程在请求lock并被阻塞时,如果被interrupt,则此线程会被唤醒并被要求处理InterruptedException*/

lock.lockInterruptibly();

try {

try {

while (count == items.length)

notFull.await();

} catch (InterruptedException ie) {

//唤醒一个等待线程。

notFull.signal();

throw ie;

}

insert(e);

} finally {

lock.unlock();

}

}

  • poll()方法,获取并移除此队列的头,如果此队列为空,则返回 null。

public E poll() {

final ReentrantLock lock = this.lock;

lock.lock();

try {

if (count == 0)

return null;

E x = extract();

return x;

} finally {

lock.unlock();

}

}

  • take()方法,获取并移除此队列的头部,在元素变得可用之前一直等待。

public E take() throws InterruptedException {

final ReentrantLock lock = this.lock;

lock.lockInterruptibly();

try {

try {

while (count == 0)

notEmpty.await();

} catch (InterruptedException ie) {

notEmpty.signal(); // propagate to non-interrupted thread

throw ie;

}

E x = extract();

return x;

} finally {

lock.unlock();

}

}

  • 使用阻塞队列实现生产者、消费者。

public class BlockQueueTest {

ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(10);

public static void main(String[] args) {

BlockQueueTest test = new BlockQueueTest();

Producer producer = test.new Producer();

Consumer consumer = test.new Consumer();

producer.start();

consumer.start();

}

class Consumer extends Thread {

public void run() {

consume();

}

private void consume() {

while (true) {

try {

queue.take();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class Producer extends Thread {

public void run() {

produce();

}

private void produce() {

while (true) {

try {

queue.put(1);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/51252.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信