Java小程序模拟生产者和消费者事件

package jave;
/*利用生产窝窝头和吃窝窝头模拟--生产者和消费者事件(线程)*/
public class ProducerConsumer {
	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Producer p = new Producer(ss);
		Consumer c = new Consumer(ss);
		new Thread(p).start();
		new Thread(c).start();		
	}
}


//窝窝头
class WoTou {
	int id;
	WoTou(int id) {
		this.id = id;
	}
	
	public String toString() {
		return "WoTou : " + id;
	}
}


//容器--篮子
class SyncStack {
	int index = 0;
	WoTou[] arrWT = new WoTou[6];
	
	public synchronized void push(WoTou wt) throws InterruptedException {
		if(index == arrWT.length) {
			this.wait();//只有当前线程被锁定,才可以wait使得线程等待
		}
		
		this.notify();//与wait对应,叫醒一个现在正在我这个对象上wait的线程
		arrWT[index] = wt;
		index++;
	}
	
	public synchronized WoTou pop() throws InterruptedException {
		if(index == 0) {
			this.wait();
		}
		
		this.notify();
		index--;
		return arrWT[index];
	}
}


//生产窝窝头
class Producer implements Runnable{
	SyncStack ss = null;
	Producer(SyncStack ss) {
		this.ss = ss;
	}
	
	public void run() {
		for(int i = 0; i < 20; i++) {
			WoTou wt = new WoTou(i);
			try {
				ss.push(wt);
				System.out.println("生产了: " + wt);
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

//消费窝窝头
class Consumer implements Runnable{
	SyncStack ss = null;
	Consumer(SyncStack ss) {
		this.ss = ss;
	}
	
	public void run() {
		for(int i = 0; i < 20; i++) {
			WoTou wt = null;
			try {
				wt = ss.pop();
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				ss.pop();
				System.out.println("消费了: " + wt);
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/wangjian530/article/details/82884868