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

import java.awt.*;

/**
 * SupplyRow makes boxes, is a process
 */
public class SupplyRow extends Row implements Runnable { //*1 Also uses a thread now
    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 ());
	}

	// Start a new thread to run us
	Thread thread = new Thread (this); //*1
	thread.start(); //*1
    }

    /**
     * Method for Runnable
     * This one never quits
     */
    public void run () { //*1
	while (true) {
	    add(); //*4 Need to keep this code in a synchronized method

	    // Since we just added to our list, need repaint
	    canvas.repaint ();

	    try {
		Thread.sleep (1000 + (int) (500 * Math.random ())); // 1-1.5 seconds
	    } catch (InterruptedException e) { }
	}
    }

    /**
     * Give away one of our boxes
     * If we have no more, WAIT till we get some, never return null.
     */
    public synchronized Box take() {
	if (boxes.size()==0) { //*2 Wait here for a notify() indicating more boxes
	    try {
		wait(); //*2
	    } catch (InterruptedException e) { }
	}

	Box ans = boxes.remove (0); //*3 At this point size must be >0, give away the box

	// Since we just decreased our list, need repaint
	canvas.repaint ();

	return ans;
    }

    /**
     * Add a new box, and wake up waiting take()
     * need this in a synchronized method
     */
    private synchronized void add () { //*4
	boxes.add (new Box ()); //*4
	notify(); //*4
    }
}
[download file]