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