您的位置:首页 > 产品设计 > UI/UE

JAVA可阻塞队列-ArrayBlockingQueue

2016-01-14 10:07 891 查看
  在前面的的文章,写了一个带有缓冲区的队列,是用JAVA的Lock下的Condition实现的,但是JAVA类中提供了这项功能,就是ArrayBlockingQueue,

  ArrayBlockingQueue是由数组支持的有界阻塞队列,次队列按照FIFO(先进先出)原则,当队列已经填满,在去增加则会导致阻塞,这种阻塞类似线程阻塞。

  ArrayBlockingQueue提供的增加和取出方法总结

抛异常返回值阻塞超时
InsertAdd(e)offer(e)put(e)offer(e,time,unit)
remove  remove()  poll()take()  poll(time,unit)  
Examine  element()peek()空  
  使用ArrayBlockingQueue的一个子类BlockingQueue实现一个可阻塞队列,一个线程put另一个线程take,当队列为空时take等待,当线程满时put等待

  此实现方式没有线程互斥

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
* 可阻塞的队列
* BlockingQueue
* 此方式不能实现线程互斥
* @author
*
*/
public class BlockingQueueCommunicationTest {
public static void main(String[] args) {
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("线程"
+ Thread.currentThread().getName() + "准备增加");
queue.put(1);
System.out.println("线程"
+ Thread.currentThread().getName() + "已增加,队列有"
+ queue.size() + "个");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("线程"
+ Thread.currentThread().getName() + "准备取走");
queue.take();
System.out.println("线程"
+ Thread.currentThread().getName() + "已取走,队列剩余"
+ queue.size() + "个");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: