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(p).start(); new Thread(p).start(); new Thread(c).start(); } } //定义一个WoTou类,在类中有id以标记是哪个窝头,重写了toString方法 class WoTou { int id; WoTou(int id) { this.id = id; } public String toString() { return "WoTou : " + id; } } //定义一个篮子的对象,用于装WoTou,在类中有push方法,用于装WoTou,pop方法,用于吃WoTou class SyncStack { int index = 0; WoTou[] arrWT = new WoTou[6]; /* *wate()只有在锁定(synchronized)的时候才能使用 */ //push用于装WoTou,当WoTou数达到6时wait()休息 public synchronized void push(WoTou wt) { while(index == arrWT.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //唤醒瓦特() this.notifyAll(); arrWT[index] = wt; index ++; } //pop用于吃WoTou,当WoTou数为0时wait() public synchronized WoTou pop() { while(index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; return arrWT[index]; } } //继承Runnable接口,实现run方法的Producer类,一个对象只生产20个WoTou 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); ss.push(wt); System.out.println("生产了:" + wt); try { Thread.sleep((int)(Math.random() * 200)); } catch (InterruptedException e) { e.printStackTrace(); } } } } //继承Runnable接口,实现run方法的Consumer类,一个对象只消费20个WoTou 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 = ss.pop(); System.out.println("消费了: " + wt); try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
时间: 2024-09-30 15:48:10