Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

public class Main {
    public static void main(String[] args) {
        ThreadGroupDemo tg = new ThreadGroupDemo();

    }
}

class ThreadGroupDemo implements Runnable {
    public ThreadGroupDemo() {
        MyThreadGroup pGroup = new MyThreadGroup("ParentThreadGroup");
        MyThreadGroup cGroup = new MyThreadGroup(pGroup, "ChildThreadGroup");

        Thread thr2 = new Thread(pGroup, this);
        System.out.println("Starting " + thr2.getName());

        thr2.start();

        // create third thread
        Thread thr3 = new Thread(cGroup, this);
        System.out.println("Starting " + thr3.getName());

        thr3.start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        thr2.interrupt();
        thr3.interrupt();

    }

    public void run() {
        try {
            System.out.print(Thread.currentThread().getName());
            System.out.println(" executing...");

            while (true) {
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            Thread currThread = Thread.currentThread();
            System.out.print(currThread.getName());
            System.out.println(" interrupted:" + e.toString());

            // rethrow the exception
            throw new RuntimeException(e.getMessage());
        }
    }
}

class MyThreadGroup extends ThreadGroup {

    MyThreadGroup(String n) {
        super(n);
    }

    MyThreadGroup(ThreadGroup parent, String n) {
        super(parent, n);
    }

    public void uncaughtException(Thread t, Throwable e) {
        System.out.println(t + " has unhandled exception:" + e);
    }
}