MyThread.java Source code

Java tutorial

Introduction

Here is the source code for MyThread.java

Source

/*
 * Output:
New thread: Thread[One,5,Group A]
New thread: Thread[Two,5,Group A]
One: 5
New thread: Thread[Three,5,Group B]
New thread: Thread[Four,5,Group B]
    
Here is output from list():
java.lang.ThreadGroup[name=Group A,maxpri=10]
Thread[One,5,Group A]
Thread[Two,5,Group A]
java.lang.ThreadGroup[name=Group B,maxpri=10]
Thread[Three,5,Group B]
Thread[Four,5,Group B]
Suspending Group A
Three: 5
Two: 5
Four: 5
Resuming Group A
Four: 4
Three: 4
Waiting for threads to finish.
Two: 4
 */

class MyThread extends Thread {
    boolean suspended;

    MyThread(String threadname, ThreadGroup tgOb) {
        super(tgOb, threadname);
        System.out.println("New thread: " + this);
        suspended = false;
        start(); // Start the thread
    }

    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println(getName() + ": " + i);
                Thread.sleep(1000);
                synchronized (this) {
                    while (suspended) {
                        wait();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Exception in " + getName());
        }
        System.out.println(getName() + " exiting.");
    }

    void suspendMe() {
        suspended = true;
    }

    synchronized void resumeMe() {
        suspended = false;
        notify();
    }
}

public class MainClass {
    public static void main(String args[]) {
        ThreadGroup groupA = new ThreadGroup("Group A");
        ThreadGroup groupB = new ThreadGroup("Group B");

        MyThread ob1 = new MyThread("One", groupA);
        MyThread ob2 = new MyThread("Two", groupA);
        MyThread ob3 = new MyThread("Three", groupB);
        MyThread ob4 = new MyThread("Four", groupB);

        System.out.println("\nHere is output from list():");
        groupA.list();
        groupB.list();

        System.out.println("Suspending Group A");
        Thread tga[] = new Thread[groupA.activeCount()];
        groupA.enumerate(tga); // get threads in group
        for (int i = 0; i < tga.length; i++) {
            ((MyThread) tga[i]).suspendMe(); // suspend each thread
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }

        System.out.println("Resuming Group A");
        for (int i = 0; i < tga.length; i++) {
            ((MyThread) tga[i]).resumeMe();
        }

        try {
            System.out.println("Waiting for threads to finish.");
            ob1.join();
            ob2.join();
            ob3.join();
            ob4.join();
        } catch (Exception e) {
            System.out.println("Exception in Main thread");
        }
        System.out.println("Main thread exiting.");
    }
}