/*
 * ThreadsDemo.java
 * Sample solution to the homework #6
 * Created on May 22, 2001, 4:47 PM
 */

// package pic20a;

import java.awt.Graphics;
import java.awt.Color;
import java.util.*;
import java.text.DateFormat;

/**
 *
 * @author  fedandr@math.ucla.edu
 * @version 1
 */
public class ThreadsDemo extends java.applet.Applet implements Runnable {
    private static final int N = 2; 
    private static final Color[] CLOCK_COLORS = {Color.red, Color.blue};
    private static final int[] CLOCK_NAPS = {1000, 1500};
     
    private ClockThread[] clockThreads = null;
    private Thread mainThread = null;

    /** Initializes the applet ThreadsDemo */
    public void init () {
        setBackground (java.awt.Color.white);
    }
    
    public void start() {
        if (mainThread == null) {
            mainThread = new Thread(this, "Clock Maddness");
            mainThread.setPriority(Thread.NORM_PRIORITY);
        }
        clockThreads = new ClockThread[N];
        for (int i = 0; i < N; i++) {
            clockThreads[i] = new ClockThread(
                    "Clock" + i, CLOCK_COLORS[i], CLOCK_NAPS[i]);
            clockThreads[i].setPriority(randPriority());
            clockThreads[i].start();
        }
        mainThread.start();
    }
    
    public void run() {
	Thread myThread = Thread.currentThread();
        while (mainThread == myThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) { }
        }
    }    
    
    public void stop() {
        for (int i = 0; i < N; i++) {
            if (clockThreads[i].isAlive()) {
                clockThreads[i] = null;
            }
        }
        mainThread = null;
    }
    
    public void paint(Graphics g) {
        for (int i = 0; i < N; i++) {
                g.setColor(clockThreads[i].color);
                g.drawString(clockThreads[i].getName() + " (priority " +
		clockThreads[i].getPriority() + "): " +
                        clockThreads[i].time, 10, 20 * (i + 1));
        }
    }
            
    static int randPriority() {
        return  (int) (Math.random() * 4 + 1);
    }


    private class ClockThread extends Thread {
        Color color = null;
        String time = null;
        int nap = 0;
        private Date date = null;
        
        ClockThread(String name, Color color, int nap) {
            super(name);
            this.color = color;
            this.nap = nap;
        }

        public void run() {
            while (true) {
                try {
		    sleep(nap);
                } catch (InterruptedException e) { }
                date = Calendar.getInstance().getTime();
                time = DateFormat.getTimeInstance().format(date);
            }
        }
    }
       
}
