生产者消费者(三)

需求: 多个生产者不断的生产产品,多个消费者不断的消费产品,仓库可以存放10个产品。 第一批产品需要生产20个产品,并消费完毕。

这里使用JDK5中的并发包中的类Lock.

package ycl.learn.effective.java.thread.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 

/**
 * 公共资源类
 */
public class PublicResourceLock {

	private int number = 0;

	private int index = 0;

	public static final int MAX_POOL = 10;

	public static final Product[] products = new Product[MAX_POOL];

	public static final int MAX_RESOURCE = 20;

	private Lock lock = new ReentrantLock();

	private Condition produced = lock.newCondition();

	private Condition consumed = lock.newCondition();

	/**
	 * 增加公共资源
	 */
	public synchronized boolean increace() {
		lock.lock();
		try {
			if (isComplete()) {// 生产任务完成
				return false;
			}

			while (isFull()) {
				produced.await();// wait
			}
			number++;
			index++;
			Product p = new Product(index);
			products[number - 1] = p;
			consumed.signalAll();// notifyAll();
			System.out.println(Thread.currentThread() + "increace:" + index);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return true;
	}

	/**
	 * 减少公共资源
	 */
	public synchronized boolean decreace() {
		lock.lock();
		try {
			while (isEmpty()) {
				if (isComplete()) {
					return false;
				} else {
					consumed.await();//wait
				}
			}
			Product p = products[number - 1];
			number--;
			produced.signalAll();//notifyAll();
			System.out.println(Thread.currentThread() + "decreace:" + p.index);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return true;
	}

	/**
	 * 判断是否满了
	 */
	public boolean isFull() {
		return number >= MAX_POOL;
	}

	/**
	 * 判断是否空了
	 */
	public boolean isEmpty() {
		return number <= 0;
	}

	/**
	 * 判断生产完毕
	 * 
	 */
	public boolean isComplete() {
		return index >= MAX_RESOURCE;
	}

	class Product {
		public int index;

		public Product(int index) {
			this.index = index;
		}
	}
}



这把锁使用了两个Condition,一个为生产者,当满的时候,produced.await,唤醒消费者
consumed.signalAll().
同理,当消费队列为空的时候,consumed.await,唤醒生产者produced.signalAll().
其实和wait/notify 模式差不多

你可能感兴趣的:(生产者消费者)