Skip to content

Thread Example

This code was written in ~2004. Since then the JDK has been changed so you will need to add a package statement and located the class in the appropriate directory in your classpath. But the lesson demonstrated is multiple long-running threads.

import java.lang.*;
import java.text.SimpleDateFormat;
import java.util.*;
class threads {
    public static String[] names = {
    "Alice", "Bob", "Christy", "David", "Erica", "Frank", "Gary", 
    "Hillary", "Ian", "Jill", "Kevin", "Linda", "Mike", "Nancy", "Owen", 
    "Percilla", "Quinn", "Rachel", "Steve", "Tawni", "Uma", "Valerie", 
    "Willy", "Yeta", "Ziggy"
    };
    public static void main(String[] args) {

    //create 10 threads and run them
    for (int i = 0; i < names.length; i++) {
        T1 t = new T1(i, names[i]);
        t.start();
    }
    }
}

class T1
    extends Thread {
    public int threadID = 0;
    public SimpleDateFormat sdf = null;
    public String name = null;
    public Random rndm = null;
    public static String[] dailyEvents = {
    "alarm went off", "hit snooze button", "alarm went off again", 
    "turned off the alarm clock and got up", "going to kitchen", 
    "eating breakfast", "cleaning up breakfast", "heading for the shower", 
    "taking a shower", "getting dressed", "driving to work", "working", 
    "getting a morning snack", "working after morning snack", 
    "going to lunch", "eating lunch", "returning from lunch", 
    "working after lunch", "getting an afternoon snack", 
    "ending the work day", "driving home", "eating dinner", "watching TV", 
    "brushing teeth", "going to bed", "sleeping"
    };
    public T1(int t, String n) {
    threadID = t;
    name = n;
    sdf = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss.SSSS");
    rndm = new Random(Calendar.getInstance().getTime().getTime() + 
              (long)t);
    say(name + " is alive.");
    }

    public void run() {
    for (int x = 0; x < dailyEvents.length; x++) {
        say(name + " " + dailyEvents[x]);
        try {
        this.yield();
        this.sleep((long)(Math.random() * 100 * 120)); // 0-2 min.
        } catch (InterruptedException ie) {
        say("InterruptedException was thrown for " + name);
        this.destroy();
        }
    }
    say(name + " is terminating.");
    }
    public void say(int threadId, String msg) {
    System.out.println(getTime() + "Thread " + threadId + ":  " + msg);
    }
    public void say(String msg) {
    System.out.println(getTime() + msg);
    }
    public String getTime() {
    return "[" + sdf.format(new Date()) + "]";
    }
}