LinkedBlockingQueue

简介

ava.util.concurrent包下的新类。LinkedBlockingQueue就是其中之一,顾名思义这是一个阻塞的线程安全的队列,底层采用链表实现。

构造方法(具体详情查看JDK API)

LinkedBlockingQueue()
创建一个LinkedBlockingQueue容量为 Integer.MAX_VALUE。
LinkedBlockingQueue(Collection<? extends E> c)
创建一个LinkedBlockingQueue容量为 Integer.MAX_VALUE,最初包含给定集合的元素,以集合迭代器的遍历顺序添加。
LinkedBlockingQueue(int capacity)
创建LinkedBlockingQueue具有给定(固定)容量的a。

方法

添加元素的方法有三个:add,put,offer。

1.add方法:add方法在添加元素的时候,若超出了度列的长度会直接抛出异常

2.put方法:对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。

3.offer方法:offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。

 

从队列中取出并移除头元素的方法有:poll,remove,take。

1.poll: 若队列为空,返回null。

2.remove:若队列为空,抛出NoSuchElementException异常。

3.take:若队列为空,发生阻塞,等待有元素。

例子:生产者消费者

共享的实例变量

public class Factory {
	BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>();

	public void produce(String put) throws InterruptedException {
		//对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。
		blockingQueue.put(put);
		System.out.println("product:" + put);
	}

	public String consume() throws InterruptedException {
		// take方法若队列为空,发生阻塞,等待有元素。
		String take = blockingQueue.take();
		System.out.println("consumer:" + take);
		return take;
	}
}

生产者

public class Product implements Runnable{
	private Factory factory;

	public Product(Factory factory) {
		this.factory = factory;
	}

	@Override
	public void run() {
		while (true) {
			try {
				factory.produce("一部手机");
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

消费者

public class Consumer implements Runnable{
	private Factory factory;

	public Consumer(Factory factory) {
		this.factory = factory;
	}

	public void run() {
		try {
			while (true) {
				// 消费苹果
				factory.consume();
				// 休眠1000ms
				Thread.sleep(1000);
			}
		} catch (InterruptedException ex) {
			System.out.println("Consumer Interrupted");
		}
	}
}

测试

public class LinkedBlockingQueueTest {

	public static void main(String[] args){
		Factory factory = new Factory();

		Product product = new Product(factory);
		Consumer consumer = new Consumer(factory);

		ExecutorService executorService = Executors.newCachedThreadPool();

		executorService.execute(product);
		executorService.execute(consumer);
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值