// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Timer;
import java.util.TimerTask;

public class TimerFun {
    public static void dumpThreads() {
        Thread[] allt = new Thread[Thread.activeCount()];
        Thread.enumerate(allt);
        for(Thread t : allt) {
            System.out.printf("%d : %s (%s)\n", t.getId(), t.getName(), t.getState().toString());
        }
    }
    public static void main(String[] args) throws InterruptedException {
        dumpThreads();
        Timer t1 = new Timer();
        dumpThreads();
        t1.scheduleAtFixedRate(new MyTimerTask("Hi A"), 0,  5000);
        dumpThreads();
        t1.scheduleAtFixedRate(new MyTimerTask("Hi B"), 0,  5000);
        dumpThreads();
        Timer t2 = new Timer();
        dumpThreads();
        t2.scheduleAtFixedRate(new MyTimerTask("Hi C"), 0,  5000);
        dumpThreads();
        t2.scheduleAtFixedRate(new MyTimerTask("Hi D"), 0,  5000);
        dumpThreads();
        Thread.sleep(20000);
        t1.cancel();
        dumpThreads();
        t2.cancel();
        dumpThreads();
    }
}

class MyTimerTask extends TimerTask {
    private String msg;
    public MyTimerTask(String msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        System.out.println(msg);
    }
}
