java 多线程(生产消费者模式)

备注说明:

该内容拷贝自网络

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

Java代码 复制代码 收藏代码
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.BlockingQueue;
  4. public class Producer implements Runnable {
  5. private BlockingQueue queue;
  6. // put producer in queue
  7. public Producer(BlockingQueue q) {
  8. this.queue = q;
  9. }
  10. public void run() {
  11. try {
  12. while (true) {
  13. // wait for a random time
  14. Thread.sleep((int) (Math.random() * 3000));
  15. queue.put(produce());
  16. }
  17. } catch (InterruptedException ex) {
  18. // catch exception
  19. }
  20. }
  21. public String produce() {
  22. List<String> product = new ArrayList<String>();
  23. String producProduct = null;
  24. product.add("Car");
  25. product.add("Phone");
  26. product.add("Plane");
  27. product.add("Computer");
  28. boolean flag = true;
  29. int getProduct = (int) (Math.random() * 3);
  30. while (flag) {
  31. if (getProduct <= product.size()) {
  32. producProduct = product.get(getProduct);
  33. flag = false;
  34. }
  35. }
  36. System.out.println("Producer producing " + producProduct);
  37. return producProduct;
  38. }
  39. }
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

Java代码 复制代码 收藏代码
  1. import java.util.concurrent.BlockingQueue;
  2. public class Consumer implements Runnable {
  3. private BlockingQueue queue;
  4. public Consumer(BlockingQueue q){
  5. this.queue=q;
  6. }
  7. @Override
  8. public void run() {
  9. // TODO Auto-generated method stub
  10. try {
  11. while (true) {
  12. // wait for a random time
  13. Thread.sleep((int) (Math.random() * 3000));
  14. consume(queue.take());
  15. }
  16. } catch (InterruptedException ex) {
  17. }
  18. }
  19. public void consume(Object x) {
  20. System.out.println("Consumer buy product "+x.toString());
  21. }
  22. }
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

Java代码 复制代码 收藏代码
  1. import java.util.concurrent.ArrayBlockingQueue;
  2. import java.util.concurrent.BlockingQueue;
  3. public class TestClient {
  4. /**
  5. * @param args
  6. */
  7. public static void main(String[] args) {
  8. // TODO Auto-generated method stub
  9. new TestClient();
  10. }
  11. public TestClient() {
  12. BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
  13. Thread producerThread = new Thread(new Producer(queue));
  14. Thread consumerThread = new Thread(new Consumer(queue));
  15. producerThread.start();
  16. consumerThread.start();
  17. }
  18. }
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、付费专栏及课程。

余额充值