使用Condition的生产者消费者模式

1.生产者消费者在处理并发时是很常用的处理方式 是很有必要掌握的。
2.Lock其实就相当于传统的synchronize Condition的await()相当于wait() signal()相当于notify().
3.没有使用传统的 wait() 和notify()的原因是 Condition可以有多个,能够用来解决更加复杂的情况.
直接上代码:

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

public class ConsumerAndProducter {

	public static void main(String[] args) {
		new ConsumerAndProducter().work();
	}

	int length = 8;// 仓库最大容量

	Lock lock = new ReentrantLock();
	Condition notFull = lock.newCondition();
	Condition notEmpty = lock.newCondition();

	List<Productor> Productors = new ArrayList<>();

	private void work() {
		new Thread(new Runnable() {
			public void run() {
				consume();
			}
		}).start();
		

		new Thread(new Runnable() {
			public void run() {
				consume();
			}
		}).start();
		

		new Thread(new Runnable() {
			public void run() {
				product();
			}
		}).start();
		
	}

	/**
	 * 消费
	 */
	private void consume() {

		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				
				e1.printStackTrace();
			}
			
			lock.lock();
			try {
				while (Productors.size() == 0) {
					System.out.println("容器为空 等待生产"+Thread.currentThread().getName());
					notEmpty.await();
				}
				Productors.remove(0);
				System.out.println("消费了一个产品"+Thread.currentThread().getName());
				System.out.println("容器有空余 通知生产"+Thread.currentThread().getName());
				notFull.signal();

			} catch (InterruptedException e) {

				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}

	}

	/**
	 * 生产
	 */
	private void product() {
		while(true){
			try {
				Thread.sleep(500); //生产效率
			} catch (InterruptedException e1) {
				
				e1.printStackTrace();
			}
			
			
			lock.lock();
			try {
				while (Productors.size() == 8) {
					System.out.println("容器已满 等待消费"+Thread.currentThread().getName());
					notFull.await();
				}

				Productors.add(new Productor()); //生产机器数
				
				System.out.println("产品已生产 通知可以消费"+Thread.currentThread().getName());
				notEmpty.signal();

			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
		
	}

	/**
	 * 产品
	 * @author z2wenfa
	 *
	 */
	private class Productor {

		public Productor() {
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值