生产者和消费者问题(BlockingQueue Implement)

本文介绍了Java 1.5及以后版本中引入的BlockingQueue接口及其主要方法。BlockingQueue是一种特殊的队列,支持等待队列非空时获取元素的操作,并在存储元素时等待队列空间可用。文章还提供了一个使用BlockingQueue实现生产者-消费者模型的例子。
摘要由CSDN通过智能技术生成

Introduce BlockingQueue:

 

BlockingQueue only support java 1.5 or higher,and it's defined as below.

 

public interface BlockingQueue<E>
extends
Queue<E>

 

As the definition,the parameters E is the type of elements helding in this collection. A Queue that  additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

 

Summay of BlockingQueue methods:(as the figure)

 

 

 Throws exceptionSpecial valueBlocksTimes out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicablenot applicable

Pls Note: A BlociingQueue does not accept null elements. Implementations throw nullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

 

Primarily designed of BlockingQueue:

 

BlockingQueue implementations are designed to be used primarily for producer-comsumer queues, but addtionally support the Collection interface. So,for example, it is possiable to remove an arbitrary element from a queue using remove(i). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

 

Of course BlockingQueue implementations are thread-safe. All queeing methods achieve their effects atomically using internal locks or other form of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example for addAll(c) to fail (throw an exception) after adding only some of the elements in c.

 

Sample of use BlockingQueue to implement Producer-Consumer Question :

 

1. Create a producer.

Producer.java

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

	private BlockingQueue queue;

	// put producer in queue
	public Producer(BlockingQueue q) {
		this.queue = q;
	}

	public void run() {
		try {
			while (true) {
				// wait for a random time
				Thread.sleep((int) (Math.random() * 3000));
				queue.put(produce());
			}
		} catch (InterruptedException ex) {
			// catch exception
		}
	}

	public String produce() {
		List<String> product = new ArrayList<String>();
		String producProduct = null;
		product.add("Car");
		product.add("Phone");
		product.add("Plane");
		product.add("Computer");
		boolean flag = true;
		int getProduct = (int) (Math.random() * 3);
		while (flag) {
			if (getProduct <= product.size()) {
				producProduct = product.get(getProduct);
				flag = false;
			}
		}
		System.out.println("Producer producing " + producProduct);
		return producProduct;
	}

}

 

2.Create a consumer.

Consumer.java

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

	private  BlockingQueue queue;

	public Consumer(BlockingQueue q){
		this.queue=q;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (true) {
				// wait for a random time
				Thread.sleep((int) (Math.random() * 3000));
				consume(queue.take());
			}
		} catch (InterruptedException ex) {
		}

	}

	public void consume(Object x) {
		System.out.println("Consumer buy product "+x.toString());
	}
}

 

3. Test Client

TestClient.java

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


public class TestClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TestClient();
	}

	public TestClient() {
		BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
		Thread producerThread = new Thread(new Producer(queue));
		Thread consumerThread = new Thread(new Consumer(queue));
		producerThread.start();
		consumerThread.start();
	}
}

 

 

 Summay:

 This sample introduces BlockingQueue Class and using it to implement the Producer-Consumer  Question.

 

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值