生产者与消费者模式之管程法

package Tread;

public class TestProduce {
	public static void main(String[] args) {
		Systack sy = new Systack();
		Shengchan sc = new Shengchan(sy);
		XiaoFei xf = new XiaoFei(sy);
		new Thread(xf).start();
		new Thread(sc).start();
	}
}

class ManTou {
	int id;

	ManTou(int x) {
		id = x;
	}

	public ManTou() {
		// TODO Auto-generated constructor stub
	}
}

class Systack {
	int index = 0;
	ManTou[] mt = new ManTou[10];

	public synchronized void push(ManTou m) {
		while (index == mt.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		mt[index] = m;
		index++;
	}

	public synchronized ManTou pop() {
		while (index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		index--;
		return mt[index];
	}
}

class XiaoFei implements Runnable {
	Systack sc = null;

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			ManTou m = sc.pop();
			System.out.println("吃馒头");
		}

	}

	public XiaoFei(Systack sc) {
		super();
		this.sc = sc;
	}

}

class Shengchan implements Runnable {
	Systack sc = null;

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			System.out.println("造馒头");
			ManTou mt = new ManTou(i);
			sc.push(mt);
		}
	}

	public Shengchan(Systack sc) {
		super();
		this.sc = sc;
	}
}

  

猜你喜欢

转载自www.cnblogs.com/yjxs/p/9849205.html