Threads And ThreadGroups In Java

Introduction

Thread creates a new thread of execution. The name of the thread is specified by the ThreadName. Thread groups are to manage groups of threads as a unit. When the user wants to suspend and resume a number of related threads then ThreadGroup is useful.

Threads 

The abstract Process class encapsulates a process (i.e, an execution program), if the user does not specify a thread name, then the Java Virtual Machine creates a default thread name.

Thread contains constructors that are listed below,

  • Thread()
  • Thread (Runnable threadOb)
  • Thread(Runnable threadOb, String threadName)
  • Thread(String threadName)
  • Thread(ThreadGroup groupOb, String threadName)

The above constructors, threadOb is an instance of a class that implements the Runnable interface. groupOb represents the thread group to which the new thread belongs. When no group is specified, the new thread belongs to the same group as the parent thread.

Methods found in Thread class

  • static int activeCount(): This method returns the number of threads in the group to which the thread belongs.
  • final ThreadGroup getThreadGroup(): Returns the ThreadGroup object of which the invoking thread is a member.
  • final void setDaemon(Boolean state): Flags the thread as a daemon thread.
  • void run():  Begins execution of a thread.

ThreadGroup

ThreadGroup creates a group of threads. It defines two constructors

  • ThreadGroup(String groupName)
  • ThreadGroup(ThreadGroup parentOb, String groupName)

Thread groups are used to manage groups of threads as a unit. ThreadGroup is useful when user wants to suspend and resume a number of related threads.

Methods found in ThreadGroup class

  • final String getName(): Returns the name of the group.
  • final ThreadGroup getParent(): Returns null if ThreadGroup object has no parent. Otherwise, it returns the parent of the invoking object.
  • void list(): Displays information about the group.
  • final Boolean parentOf(ThreadGroup group): Returns true if the invoking thread is the parent of group (or group itself). Otherwise, it returns false.
  • String toString(): Returns the string equivalent of the group.

The example illustrates the thread group.

class NewThread extends Thread {
    boolean sFlag;
    NewThread(String threadName, ThreadGroup tgOb) {
        super(tgOb, threadName);
        System.out.println("New Thread is" + this);
        sFlag = false;
        start();
    }
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println(getName() + "i" + i);
                Thread.sleep(1000);
                synchronized(this) {
                    while (sFlag) {
                        wait();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Exception in" + getName());
        }
        System.out.println(getName() + "editing.");
    }
    void mysus() {
        sFlag = true;
    }
    synchronized void myres() {
        sFlag = false;
        notify();
    }
}
class ThreadGroupDemo {
    public static void main(String args[]) {
        ThreadGroup groupA = new ThreadGroup("Group A");
        ThreadGroup groupB = new ThreadGroup("Group B");
        NewThread ob1 = new NewThread("One", groupA);
        NewThread ob2 = new NewThread("Two", groupA);
        NewThread ob3 = new NewThread("Three", groupB);
        NewThread ob4 = new NewThread("Four", groupB);
        System.out.println("Output from the list():");
        groupA.list();
        groupB.list();
        System.out.println("Now Group A is suspended");
        Thread tga[] = new Thread[groupA.activeCount()];
        groupA.enumerate(tga);
        for (int i = 0; i < tga.length; i++) {
            ((NewThread) tga[i]).mysus();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            System.out.println("Main Thread interrupted");
            System.out.println("Resuming  Group A");
            for (int i = 0; i < tga.length; i++) {
                ((NewThread) tga[1]).myres();
            }
        }
        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");
    }
}
  • Save the file ThreadGroupDemo.java
  • Compile the file using javac ThreadGroupDemo.java
  • Run the file using java ThreadGroupDemo

Output

Summary

Thread creates a new thread of execution. The name of the thread is specified by the ThreadName. Thread groups are to manage groups of threads as a unit. When the user wants to suspend and resume a number of related threads then ThreadGroup is useful.


Similar Articles