MyThread.java Source code

Java tutorial

Introduction

Here is the source code for MyThread.java

Source

class MyThread extends Thread {
    MyThread(ThreadGroup group, String name) {
        super(group, name);
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + " starting.");
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.print(Thread.currentThread().getName());
            System.out.println(" interrupted.");
        }
        System.out.println(Thread.currentThread().getName() + " exiting.");
    }
}

public class Main {

    public static void main(String args[]) throws Exception {

        ThreadGroup group = new ThreadGroup("new Group");

        MyThread t1 = new MyThread(group, "Thread1");
        MyThread t2 = new MyThread(group, "Thread2");

        t1.start();
        t2.start();

        Thread.sleep(1000);

        System.out.println(group.activeCount() + " threads in thread group...");

        Thread th[] = new Thread[group.activeCount()];
        group.enumerate(th);
        for (Thread t : th) {
            System.out.println(t.getName());
        }
        Thread.sleep(1000);

        System.out.println(group.activeCount() + " threads in thread group...");

        group.interrupt();
    }
}