java并发编程(13)--ArrayBlockingQueue

本文介绍ArrayBlockingQueue,一种由数组支持的有界阻塞队列,遵循FIFO原则。文章详细解释了其作为典型“有界缓存区”的工作原理,并提供了一个生产者消费者模式的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.BlockingQueue接口:

public interface BlockingQueue<E>
    
      extends
      Queue<E>


     抛出异常     特殊值     阻塞     超时
插入     add(e)     offer(e)     put(e)     offer(e, time, unit)
移除     remove()     poll()     take()     poll(time, unit)
检查     element()     peek()     不可用     不可用


2.ArrayBlockingQueue

接口 BlockingQueue<E>

类型参数:
    E - 在此 collection 中保持的元素类型

所有超级接口:
    Collection<E>, Iterable<E>, Queue<E>

所有已知子接口:
    BlockingDeque<E>

所有已知实现类:
    ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue 


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

这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致操作受阻塞;试图从空队列中提取元素将导致类似阻塞。

此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。默认情况下,不保证是这种排序。然而,通过将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。 

eg:

package com.qunar.thread;

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

public class ArrayBlockingQueue {
	public static void main(String[] args) {
		final BlockingQueue<Integer> queue = new java.util.concurrent.ArrayBlockingQueue<Integer>(3);
		for(int i =0;i<2;i++){
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					while (true) {
						try {
							Thread.sleep((long) Math.random() * 10000);
							System.out.println(Thread.currentThread().getName()
									+ "准备放数据");
							int data = new Random().nextInt();
							queue.put(data);
							System.out.println(Thread.currentThread().getName()
									+ "已經放入數據:" + data);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(10000);
						System.out.println(Thread.currentThread().getName()
								+ "准备取数据");
						int data = queue.take();
						System.out.println(Thread.currentThread().getName()
								+ "取得数据:" + data+",目前隊列中有"+queue.size()+"個數據");
						
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}
		}).start();
	}
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值