Threads1: Row.java

import java.awt.*;
import java.util.concurrent.*; //*4 We maintain list of our Box's

/**
 * A process that grabs Box's and draws a row of them
 */
public class Row implements Runnable { //*1 We use a thread
    private Canvas canvas;
    private Rectangle loc;
    private CopyOnWriteArrayList<Box> boxes = new CopyOnWriteArrayList<Box> (); //*4

    public Row (Rectangle loc, Canvas canvas) {
	this.loc = loc;
	this.canvas = canvas;

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

    /**
     * Method for Runnable
     */
    public void run () { //*2 What thread does when you run() it
	for (int i=0; i<10; i++) { //*2
	    boxes.add (new Box ()); //*2
	    // Since we've just changed our box list, request a repaint
	    canvas.repaint (); //*2

	    try {
		Thread.sleep (2000 + (int) (500 * Math.random ())); // 2-2.5 seconds //*2
	    } catch (InterruptedException e) { }
	}
	System.out.println ("Row at y = " + loc.y + " finished"); //*3 Thread is about to die, print message
    }
	
    public void draw (Graphics g) {
	Graphics2D g2 = (Graphics2D) g;

	g2.draw (loc);

	// We tell each Box where to draw itself
	int boxsize = loc.height-2*5;
	Rectangle boxloc = new Rectangle (loc.x+10, loc.y+5,
					  boxsize, boxsize);

	// Draw each of our Box's
	for (Box b: boxes) { //*4
	    b.draw (g, boxloc); //*4
	    boxloc.x = boxloc.x + boxsize + 10; //*4
	}
    }
}
[download file]