容器: public class SynList { private int index = 0; private static final int MAX = 5; private Wotou []data = new Wotou[MAX]; public synchronized void push(Wotou wotou){ while (index == MAX){ System.out.println("已满"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("add id:"+wotou.getId()); data[index] = wotou; index++; this.notifyAll(); } public synchronized Wotou pop(){ while (index == 0){ System.out.println("已空"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } index--; System.out.println("pop index:"+index); Wotou wotou = data[index]; System.out.println("remove id:"+wotou.getId()); this.notifyAll(); return wotou; } public static void main(String[] args) { SynList list = new SynList(); new Thread(new Productor(list)).start(); new Thread(new Consumer(list)).start(); } }
生产者: public class Productor implements Runnable{ private SynList list ; public Productor(SynList list ){ this.list = list; } @Override public void run() { for (int i = 0; i < 20; i++) { Wotou wt = new Wotou(String.valueOf(i)); list.push(wt); try { Thread.sleep((int)Math.random()*200); } catch (InterruptedException e) { e.printStackTrace(); } } } }
消费者:
public class Consumer implements Runnable{ private SynList list ; public Consumer(SynList list ){ this.list = list; } @Override public void run() { for (int i = 0; i < 20; i++) { Wotou wtTo = list.pop(); System.out.println("消费:" + wtTo); try { Thread.sleep((int)Math.random()*1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }