Threads3 (other files are same as Threads1 and Threads2)

File: java/Threads3/SupplyRow.java

import java.awt.*;
import java.util.*;

/**
 * SupplyRow makes boxes, is a process
 */
public class SupplyRow extends Row implements Runnable {
    public SupplyRow (Rectangle loc, MyCanvas 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);
	thread.start();
    }

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

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

	    try {
		Thread.currentThread().sleep (500); // 1/2 second
	    } 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() {
	while (boxes.size()==0) {
	    try {
		wait();
	    } catch (InterruptedException e) { }
	}

	// Now size must be >0
	Box ans = (Box) boxes.remove (0);

	// 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 () {
	boxes.add (new Box ());
	notify();
    }
}