How do I check whether a thread group has been destroyed?

You can use ThreadGroup.isDestroyed() method to check whether a thread group and its subgroups has been destroyed.

package org.kodejava.lang;

public class CheckGroupDestroy {
    public static void main(String[] args) {
        ThreadGroup grandParent = new ThreadGroup("GrandParent");
        ThreadGroup uncle = new ThreadGroup(grandParent, "Uncle");
        ThreadGroup parent = new ThreadGroup(grandParent, "Parent");
        ThreadGroup son = new ThreadGroup(parent, "Son");
        ThreadGroup daughter = new ThreadGroup(parent, "Daughter");
        ThreadGroup neighbour = new ThreadGroup("Neighbour");

        ThreadGroup[] groupArray = {
                grandParent, uncle, parent, son, daughter, neighbour
        };

        // Destroy 'parent' group and all its subgroups
        parent.destroy();

        // Check whether the group is destroyed. The result is,
        // GrandParent, Uncle, and Neighbour did not destroyed
        // because they are not Parent's subgroups
        for (ThreadGroup tg : groupArray) {
            if (tg.isDestroyed()) {
                System.out.println(tg.getName() + " is destroyed");
            } else {
                System.out.println(tg.getName() + " is not destroyed");
            }
        }
    }
}

The result is:

GrandParent is not destroyed
Uncle is not destroyed
Parent is destroyed
Son is destroyed
Daughter is destroyed
Neighbour is not destroyed

How do I destroy a thread group?

You can destroy a thread group by using destroy() method of ThreadGroup class. It will cleans up the thread group and removes it from the thread group hierarchy. It’s not only destroy the thread group, but also all its subgroups.

The destroy() method is of limited use: it can only be called if there are no threads presently in the thread group.

package org.kodejava.lang;

public class ThreadGroupDestroy {
    public static void main(String[] args) {
        ThreadGroup root = new ThreadGroup("Root");
        ThreadGroup server = new ThreadGroup(root, "ServerGroup");
        ThreadGroup client = new ThreadGroup(root, "ClientGroup");

        // Destroy 'root' thread groups and all its subgroup
        // ('server' & 'client')
        root.destroy();

        // Check if 'root' group and its subgroups already destroyed
        if (root.isDestroyed()) {
            System.out.println("Root group is destroyed");
        }

        if (server.isDestroyed()) {
            System.out.println("Server group is destroyed");
        }

        if (client.isDestroyed()) {
            System.out.println("Client group is destroyed");
        }
    }
}

How do I count active thread in a thread group?

This example describe how to get the number of active threads in this thread group. The result might not reflect concurrent activity, and might be affected by the presence of certain system threads.

Due to the inherently imprecise nature of the result, it is recommended that this method only be used for informational purposes.

package org.kodejava.lang;

public class ThreadGroupActiveThread {
    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("TestThread");

        Thread t1 = new Thread(threadGroup, new Server(), "Server1");
        Thread t2 = new Thread(threadGroup, new Server(), "Server2");
        Thread t3 = new Thread(threadGroup, new Server(), "Server3");
        Thread t4 = new Thread(threadGroup, new Server(), "Server4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();

        // Get an estimate number of active thread of the thread
        // group.
        int activeThread = threadGroup.activeCount();
        System.out.format("Number of active threads of %s is %d %n",
                threadGroup.getName(), activeThread);
    }
}

class Server implements Runnable {
    public void run() {
        System.out.println("Running..");
    }
}

How do I get number of active thread in current thread?

In this example you’ll see how to obtain the number of active thread in the current thread. You can use the Thread.activeCount() method to get this information.

package org.kodejava.lang;

public class CountActiveThread {
    public static void main(String[] args) {
        Thread t = new Thread(() -> System.out.println("Hello..."));
        t.start();

        // Get the number of active threads in the current thread's
        // thread group.
        int activeThread = Thread.activeCount();
        System.out.format("Number of active threads of %s is %d %n",
                Thread.currentThread().getName(), activeThread);
    }
}

How do I get number of active thread group?

Use method activeGroupCount() of ThreadGroup class to get estimate number of active groups in the thread group and use activeCount() to get estimate number of active threads in a thread group.

package org.kodejava.lang;

public class ActiveGroupCount {
    public static void main(String[] args) {
        ThreadGroup root = new ThreadGroup("RootGroup");
        ThreadGroup server = new ThreadGroup(root, "ServerGroup");
        ThreadGroup client = new ThreadGroup(root, "ClientGroup");

        Thread t1 = new Thread(server, new ServerThread(), "ServerThread");
        Thread t2 = new Thread(client, new ClientThread(), "ClientThread");

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

        // Get estimate active groups in 'root' thread group
        int activeGroup = root.activeGroupCount();
        System.out.format("Estimated active group in %s is %d%n",
                root.getName(), activeGroup);

        // Get estimate active threads in 'root' thread group
        int activeThread = root.activeCount();
        System.out.format("Estimated active thread in %s is %d%n",
                root.getName(), activeThread);
    }
}

class ServerThread implements Runnable {
    public void run() {
        System.out.println("Running - Server Thread..");
    }
}


class ClientThread implements Runnable {
    public void run() {
        System.out.println("Running - Client Thread..");
    }
}

The example above print the following example output:

Estimated active group in RootGroup is 2
Estimated active thread in RootGroup is 2
Running - Client Thread..
Running - Server Thread..

How do I get thread group of a thread?

Use the getThreadGroup() method of Thread class to get the thread group to which the thread belongs.

package org.kodejava.lang;

public class GetThreadGroup {
    public static void main(String[] args) {
        // Create thread groups
        ThreadGroup group = new ThreadGroup("ThreadGroup");
        ThreadGroup anotherGroup = new ThreadGroup(group, "AnotherGroup");

        // Create threads and placed into thread group
        Thread t1 = new Thread(group, new FirstThread(), "Thread1");
        Thread t2 = new Thread(anotherGroup, new FirstThread(), "Thread2");

        // Start the threads
        t1.start();
        t2.start();

        // Use getThreadGroup() method of Thread class to get the object
        // of ThreadGroup then use the getName() method to get the name
        // of thread group.
        System.out.format("%s is a member of %s%n", t1.getName(),
                t1.getThreadGroup().getName());
        System.out.format("%s is a member of %s%n", t2.getName(),
                t2.getThreadGroup().getName());
    }
}

class FirstThread implements Runnable {
    public void run() {
        System.out.println("Start..");
    }
}

How do I get the state of a thread?

To get the state of a thread use getState() method of a Thread class. One thing to be noted is that this method is designed for use in monitoring of the system state, not for synchronization control.

package org.kodejava.lang;

public class GetThreadState implements Runnable {
    public static void main(String[] args) {
        Thread thread = new Thread(new GetThreadState());
        thread.start();

        // Get the state of the thread.
        Thread.State state = thread.getState();
        System.out.println("State: " + state.name());
    }

    public void run() {
        System.out.println("Start..");
    }
}

How do I create a thread synchronized block?

The objective of thread synchronization is to ensure that when several threads want access to a single resource, only one thread can access it at any given time.

You can manage synchronization of your program at method level (synchronized method) or at block level (synchronized block). To make a block of code synchronized you can use the synchronized keyword.

The example below show how you can use the synchronized keyword.

  • Incrementor class
package org.kodejava.lang;

public class Incrementor {
    private int count;

    // A synchronized method example.
    public synchronized void increment(int value) {
        count += value;
        System.out.println(Thread.currentThread().getName() +
                ": inc >>> " + count);
    }

    public void decrement(int value) {
        // A synchronized block example the use the current object instance
        // as the monitor object.
        synchronized (this) {
            count -= value;
            System.out.println(Thread.currentThread().getName() +
                    ": dec >>> " + count);
        }
    }
}
  • IncrementThread class
package org.kodejava.lang;

public class IncrementThread implements Runnable {
    private final Incrementor incrementor;

    public IncrementThread(Incrementor incrementor) {
        this.incrementor = incrementor;
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            incrementor.increment(i * 10);
            incrementor.decrement(i * 2);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • IncrementorDemo class
package org.kodejava.lang;

public class IncrementorDemo {
    public static void main(String[] args) {
        Incrementor incrementor = new Incrementor();

        Thread t1 = new Thread(new IncrementThread(incrementor), "T1");
        Thread t2 = new Thread(new IncrementThread(incrementor), "T2");

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

Here an example result printed by the program:

T1: inc >>> 10
T1: dec >>> 8
T2: inc >>> 18
T2: dec >>> 16
T1: inc >>> 36
T1: dec >>> 32
T2: inc >>> 52
T2: dec >>> 48
T1: inc >>> 78
T1: dec >>> 72
T2: inc >>> 102
T2: dec >>> 96
T1: inc >>> 136
T1: dec >>> 128
T2: inc >>> 168
T2: dec >>> 160
T1: inc >>> 210
T1: dec >>> 200
T2: inc >>> 250
T2: dec >>> 240

How do I get the currently executing thread?

To get the currently executing thread, use the static currentThread() method of the Thread class. This method returns a reference of the currently executing thread object.

package org.kodejava.lang;

public class GetCurrentThreadDemo {
    public static void main(String[] args) {
        // Get the currently executing thread object
        Thread thread = Thread.currentThread();
        System.out.println("Id      : " + thread.getId());
        System.out.println("Name    : " + thread.getName());
        System.out.println("Priority: " + thread.getPriority());
    }
}

The code snippet print the following output:

Id      : 1
Name    : main
Priority: 5

How do I set and get the name of a thread?

You can assign a name to thread instance by using the setName() method and get the name of the thread using the getName() method. The naming support is also available as a constructor of the Thread class such as Thread(String name) and Thread(Runnable target, String name).

package org.kodejava.lang;

public class ThreadNameDemo extends Thread {
    public ThreadNameDemo() {
    }

    public ThreadNameDemo(String name) {
        super(name);
    }

    public static void main(String[] args) {
        Thread thread1 = new ThreadNameDemo();
        thread1.setName("FOX");
        thread1.start();

        Thread thread2 = new ThreadNameDemo("DOG");
        thread2.start();
    }

    @Override
    public void run() {
        // Call getName() method to get the thread name of this
        // thread object.
        System.out.println("Running [" + this.getName() + "]");
    }
}