Computer Science 122
Thread Example

/* An applet that illustrates the use of a TextArea and threads. To run this applet, click on Fruit.html .*/

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Fruit extends Applet
{
    protected TextArea fruitList;
    private FruitThread apple, orange;
    private Button Start;

    public void init ()
    {
        fruitList = new TextArea ("Threads Example", 16, 20);
        setBackground (Color.cyan);
        fruitList.setBackground (Color.white);
        add (fruitList);
        Start = new Button ("Start");
        Start.addActionListener (new startListener ());
        add (Start);
        apple = new FruitThread (this, "Apple");
        orange = new FruitThread (this, "Orange");
    } // method init

    class startListener implements ActionListener
    {
        public void actionPerformed (ActionEvent e)
        {
            apple.start ();
            orange.start ();
        }
    } // class startListener
} // class Fruit

class FruitThread extends Thread
{
    private Fruit fruitApplet;
    private String fruitType;
    private int snooze = 5;

    FruitThread (Fruit fruitApplet, String fruitType)
    {
        this.fruitApplet = fruitApplet;
        this.fruitType = fruitType;
    } // constructor

    public void run ()
    {
        for (int count = 0; count < 10; count ++)
        {
            fruitApplet.fruitList.append ('\n' + fruitType + count );
            try
            {sleep (snooze*100);
            } catch (InterruptedException e) {}
        }
    } // method run
} // FruitThread