publicstaticvoidmain(String[] args){ new Producer().start(); new ConsumerA().start(); new ConsumerB().start(); } }
classProducerextendsThread{ privatevoidproduce(){ Goods store = Goods.getInstance();
// do produce long product = new Random().nextLong(); // put into store synchronized (store) { System.out.println("生产产品:" + product); Goods.goodList.add(product); } }
@Override publicvoidrun(){ int count = 3; while (true) { long sleepTime = new Random().nextInt(10) * 100; try { Thread.sleep(sleepTime); } catch (Exception e) { // TODO: handle exception } this.produce(); if (count-- < 0) { break; } }
return; } }
classConsumerAextendsThread{ privatevoidconsumer(){ Goods store = Goods.getInstance();
synchronized (store) { Long product = Goods.goodList.getFirst(); Goods.goodList.remove(product); System.out.println("消费产品:" + product); } } @Override publicvoidrun(){ while (true) { long sleepTime = new Random().nextInt(10) * 100;