<找工作 十>生产者 消费者模型

 今天被问了个这个问题,脑子当时给抽筋了,完全给木掉了,回来好好写了边,怎么会当时写不出来呢。。。

 

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

public class Test421 extends Thread {
	public void run() {
		Customer a = new Customer();
		a.start();
		Producer b = new Producer();
		b.start();
	}

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

	int key = 0;
	Lock lock = new ReentrantLock();
	Condition condempty = lock.newCondition();
	Condition condfull = lock.newCondition();

	class Customer extends Thread {
		public void run() {
			while (true) {

				lock.lock();

				try {
					while (key < 1) {
						// System.out.println("await");
						condempty.await();
						// System.out.println("start");
					}
					System.out.println("消费了" + key);
					key--;
					condfull.signalAll();
					lock.unlock();

					// return ;
					Thread.sleep(12);

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	class Producer extends Thread {
		public void run() {
			while (true) {
				try {
					// Thread.sleep(50);
					lock.lock();
					while (key >= 1000) {
						condfull.await();
					}

					// a++;
					key++;
					System.out.println("生产了" + key);

					// Thread.sleep(5000);
					condempty.signalAll();
					lock.unlock();

					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
 

锁和条件这种方式比较重要的一点要注意的是:就算condition.sigalAll();别的线程也一定要等到lock的释放才可以继续下去,换句话说,await的时候很重要的一点是他会阻塞掉,并且隐含的会释放掉锁,这很关键,只有这样别的线程才能获得锁,才能继续执行下去。

而  sigalAll  的时候并不执行释放锁操作,只有显示的调用lock.unlock后,锁才被释放。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值