生产者和消费者

public class ProduceConsume {

	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Produce p = new Produce(ss);
		Consume c = new Consume(ss);
		
		Thread tp = new Thread(p);
		Thread tc = new Thread(c);
		
		tp.start();
		tc.start();
	}
}

class SteamBread{
	int id;
	SteamBread(int id){
		this.id = id;
	}
	public String toString() {
		return "SteamBread [id=" + id + "]";
	}
}

class SyncStack{
	int index = 0;
	SteamBread [] stb = new SteamBread [6];
	
	public synchronized void push(SteamBread sb) {
		while(index == stb.length) {
			try {
				this.wait();
				System.out.println("---当前框已满,请稍后再生产---");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		stb[index] = sb;
		index++;
	}
	
	public synchronized SteamBread pop() {
		while(index == 0) {
			try {
				this.wait();
				System.out.println("---当前框已空,请稍后再取---");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		index--;
		return stb[index];
	}
}

class Produce implements Runnable{

	SyncStack ss = null;
	
	Produce(SyncStack ss){
		this.ss = ss;
	}
	
	public void run() {
		for (int i = 0; i < 20; i++) {
			SteamBread sb = new SteamBread(i);
			ss.push(sb);
			System.out.println("生产了"+sb);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

class Consume implements Runnable{
	SyncStack ss = null;

	Consume(SyncStack ss){
		this.ss = ss;
	}
	
	public void run() {
		for (int i = 0; i < 20; i++) {
			SteamBread sb = ss.pop();
			System.out.println("消费了"+sb);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

程序运行后结果如下:

posted @ 2020-09-21 16:43  JW_Chen9596  阅读(85)  评论(0)    收藏  举报