Home » Java programming language

Java Thread Class static int activeCount() method with Example

Java Thread Class static int activeCount() method: Here, we are going to learn about the static int activeCount() method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 17, 2019

Thread Class static int activeCount()

  • This method is available in package java.lang.Thread.activeCount().
  • This method is static so this method is accessible with the classname too like this Thread.activeCount().
  • This method is used to return the number of active threads in the current threads thread group.
  • The return type of this method is int so it returns an integer type value and the active thread will be count in numbers.
  • This method does not raise an exception when no active thread is live.

Syntax:

    static int activeCount(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is int, it counts active threads in numbers.

Java program to demonstrate example of activeCount() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because it is 
    imported by default
*/

import java.lang.Thread;

public class MainThread {

    public static void main(String[] args) {
        // By using currentThread() of Thread class will return a 
        // reference of currently executing thread.
        Thread th = Thread.currentThread();

        // By using setName() method we are setting the name 
        // of current executing thread
        th.setName("Main Thread");

        // By using setPriority() method we are setting the priority of 
        // current executing thread
        th.setPriority(2);

        //Display Current Executing Thread
        System.out.println("Currently Executing Thread is :" + th);

        int active_thread = Thread.activeCount();

        // Display the number of active threads in current threads thread group
        System.out.println("The Number of active threads is : " + active_thread);

        Thread[] thread = new Thread[active_thread];

        // active_thread keep in the array
        Thread.enumerate(thread);

        // Loop for printing active thread if we have more than one thread.
        for (int i = 0; i < active_thread; ++i)
            System.out.println("Display active threads is " + thread[i]);
    }
}

Output

E:\Programs>javac MainThread.java

E:\Programs>java MainThread
Currently Executing Thread is :Thread[Main Thread,2,main]
The Number of active threads is : 1
Display active threads is Thread[Main Thread,2,main]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.