Threads2 (other files are same as before): SupplyRow.java

import java.awt.*;

/**
 * SupplyRow starts with fixed list of Box's and gives them away,
 * is not a process
 */
public class SupplyRow extends Row { //*1 Passive object, NOT a thread
    public SupplyRow (Rectangle loc, Canvas canvas) {
	super (loc, canvas);

	// Our initial set of boxes
	for (int i=0; i<22; i++) {
	    boxes.add (new Box ());
	}
    }

    /**
     * Give away one of our boxes
     * Need a single, "synchronized" routine
     * that reports whether we have any to give
     * AND takes it ("test and set")
     * So this routine tries to give a box,
     * returns the Box if succeeds, or null if fails
     */
    public synchronized Box take() { //*2 Need synchronized method
	if (boxes.size()>0) { //*3 Tests and takes in one uninterruptible unit
	    Box ans = boxes.remove (0); //*3
	    canvas.repaint (); //*4 Since we just decreased our list, need repaint
	    return ans; //*3
	}
	else return null; //*3
    } //*2
}
[download file]