import java.util.Enumeration; import java.util.Vector; import jds.Queue; import jds.collection.LinkedList; class Pastry { public Pastry (double w, String n) { weight = w; name = n; } public final double weight; public final String name; public String toString () { return name; } } class Box { public Box () { w = 0; pastries = new Vector(); } private double w; // weight of pastries private Vector pastries; // pastries public void addPastry (Pastry p) { pastries.addElement(p); w += p.weight; } public double weight () { return w; } public String toString () { String result = "Box with "; Enumeration e = pastries.elements(); while (e.hasMoreElements() ) { Pastry p = (Pastry) e.nextElement(); result = result + " " + p; } return result; } } class RandomInteger { RandomInteger (int m) { max = m; } private int max; public int intValue() { return (int) (max * Math.random()); } } class PastryProducer extends Thread { public PastryProducer (Queue q, Pastry p, RandomInteger r) { que = q; example = p; rand = r; } private Queue que; private Pastry example; private RandomInteger rand; public void run () { while (true) { // produce pastry que.addLast(example); // and sleep while (rand.intValue() != 1) try { sleep(20); } catch(Exception e) { } } } } class PastryBoxer extends Thread { public PastryBoxer (Queue q) { que = q; } private Queue que; public void run () { int boxcount = 0; Box currentBox = new Box(); while (true) synchronized (que) { if (! que.isEmpty()) { Pastry p = (Pastry) que.getFirst(); que.removeFirst(); currentBox.addPastry(p); if (currentBox.weight() > 12) { System.out.println(currentBox); if (boxcount++ > 10) System.exit(0); currentBox = new Box(); } } } } } class PastryFactorySimulation { public static void main (String [ ] args) { Queue que = new LinkedList(); PastryProducer m1 = new PastryProducer (que, new Pastry(0.25, "cookie"), new RandomInteger(3)); PastryProducer m2 = new PastryProducer (que, new Pastry(1.25, "donut"), new RandomInteger(7)); PastryProducer m3 = new PastryProducer (que, new Pastry(2.0, "eclaire"), new RandomInteger(15)); PastryBoxer c = new PastryBoxer(que); m1.start(); m2.start(); m3.start(); c.start(); } }