1. 程式人生 > >十九、併發程式設計之通過生產者消費者模型理解等待喚醒機制

十九、併發程式設計之通過生產者消費者模型理解等待喚醒機制

  • 生產者
//生產者
public class PushTarget implements Runnable{
	private Tmail tmail;//銷售平臺
	public PushTarget(Tmail tmail) {
		this.tmail = tmail;
	}
	@Override
	public void run() {
		while(true) {//無限迴圈
			tmail.push();//生產
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace
(); } } } }
  • 消費者
//消費者
public class TakeTarget implements Runnable{
	private Tmail tmail;//銷售平臺
	public TakeTarget(Tmail tmail) {
		this.tmail = tmail;
	}
	@Override
	public void run() {
		while(true) {//無限迴圈
			tmail.take();//消費
			try {
				Thread.sleep(1000);
			} catch (InterruptedException
e) { e.printStackTrace(); } } } }
  • 銷售平臺
public class Tmail {
	private int count;//產品數量
	public final int MAX_COUNT=10;//產品最大數量
	//生產
	//使用等待喚醒機制,必須加synchronized
	public synchronized void push() {
		while(count>=MAX_COUNT) {//產品數量大於等於最大數量,生產者等待
			try {
				System.out.println(Thread.currentThread
().getName()+"庫存達到上線,生產者停止生產。。。。。"); wait();//等待 } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().getName()+"生產者生產,當前庫存為:"+count); notifyAll();//喚醒 } //消費 //使用等待喚醒機制,必須加synchronized public synchronized void take() { while(count<=0) {// 產品數量為0,消費者等待 try { System.out.println(Thread.currentThread().getName()+"當前庫存為:"+count+",消費者等待。"); wait();//等待 } catch (InterruptedException e) { e.printStackTrace(); } } count--; System.out.println(Thread.currentThread().getName()+"消費者消費。"); notifyAll();//喚醒 } public static void main(String[] args) { Tmail tmail = new Tmail(); PushTarget t = new PushTarget(tmail); TakeTarget t2 = new TakeTarget(tmail); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t2).start(); new Thread(t2).start(); new Thread(t2).start(); new Thread(t2).start(); new Thread(t2).start(); new Thread(t2).start(); new Thread(t2).start(); } }