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.example.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.example.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.example.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.example.lang;

public class CountActiveThread {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                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.example.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:

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

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.example.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.example.lang;

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

    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());
    }
}

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

package org.kodejava.example.lang.thread;

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

package org.kodejava.example.lang.thread;

public class IncrementThread implements Runnable {
    private 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

package org.kodejava.example.lang.thread;

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 use join method to wait for threads to finish?

If you want a thread to work until another thread dies, you can join the thread onto the end of the another thread using the join() method. For example, you want thread B only work until thread A completes its work, then you want thread B to join thread A.

package org.kodejava.example.lang;

public class ThreadJoin implements Runnable {
    private int numberOfLoop;

    private ThreadJoin(int numberOfLoop) {
        this.numberOfLoop = numberOfLoop;
    }

    public void run() {
        System.out.println("[" +
            Thread.currentThread().getName() + "] - Running.");

        for (int i = 0; i < this.numberOfLoop; i++) {
            System.out.println("[" +
                Thread.currentThread().getName() + "] " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("[" +
            Thread.currentThread().getName() + "] - Done.");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadJoin(10), "FirstThread");
        Thread t2 = new Thread(new ThreadJoin(20), "SecondThread");

        try {
            // start t1 and waits for this thread to die before
            // starting the t2 thread.
            t1.start();
            t1.join();

            // start t2
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

How do I set the priority of a thread?

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). A thread gets a default priority that is the priority of the thread of execution that creates it.

But, you can also set a thread’s priority directly by calling the setPriority() method on a Thread instance. One thing to remember about thread priorities is never rely on thread priorities, because thread-scheduling priority behavior is not guaranteed.

package org.kodejava.example.lang;

public class ThreadPriority extends Thread {
    private String threadName;

    ThreadPriority(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        System.out.println("Running [" + threadName + "]");
        for (int i = 1; i <= 10; i++) {
            System.out.println("[" + threadName + "] => " + i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPriority thread1 = new ThreadPriority("First");
        ThreadPriority thread2 = new ThreadPriority("Second");
        ThreadPriority thread3 = new ThreadPriority("Third");
        ThreadPriority thread4 = new ThreadPriority("Fourth");
        ThreadPriority thread5 = new ThreadPriority("Fifth");

        // set thread1 to minimum priority = 1
        thread1.setPriority(Thread.MIN_PRIORITY);

        // set thread2 to priority 2
        thread2.setPriority(2);

        // set thread3 to normal priority = 5
        thread3.setPriority(Thread.NORM_PRIORITY);

        // set thread4 to priority 8
        thread4.setPriority(8);

        // set thread5 to maximum priority = 10
        thread5.setPriority(Thread.MAX_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}