Java Thread activeCount() 方法



描述

Java Thread activeCount() 方法返回當前執行緒的執行緒組中活動執行緒的數量。

宣告

以下是 java.lang.Thread.activeCount() 方法的宣告

public static int activeCount()

引數

返回值

此方法返回當前執行緒的執行緒組中活動執行緒的數量。

異常

示例:在單執行緒程式中獲取活動執行緒計數

以下示例演示了 Java Thread activeCount() 方法的使用。在這個程式中,我們建立了一個類 ThreadDemo。在 main 方法中,使用 currentThread() 方法檢索當前執行緒並打印出來。使用 activeCount(),檢索活動執行緒的計數並打印出來。接下來,我們建立了一個活動執行緒陣列並迭代它們以在控制檯上列印。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      
      // set thread priority to 1
      t.setPriority(1);
     
      // prints the current thread
      System.out.println("Thread = " + t);

      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
    
      Thread th[] = new Thread[count];
      // returns the number of threads put into the array 
      Thread.enumerate(th);
    
      // prints active threads
      for (int i = 0; i < count; i++) {
         System.out.println(i + ": " + th[i]);
      }
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Thread = Thread[Admin Thread,1,main]
currently active threads = 1
0: Thread[Admin Thread,1,main]

示例:在多執行緒程式中獲取活動執行緒計數

以下示例演示了 Java Thread activeCount() 方法的使用。在這個程式中,我們建立了一個執行緒類 ThreadDemo,它實現了 Runnable 介面。在建構函式中,使用 currentThread() 方法檢索當前執行緒,並使用 new Thread 建立一個新執行緒。使用 activeCount(),檢索活動執行緒的計數並打印出來。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   ThreadDemo() {
      // main thread
      Thread currThread = Thread.currentThread();
      
      // thread created
      Thread t = new Thread(this, "Admin Thread");
      
      // this will call run() function
      t.start();
      int count = Thread.activeCount();
      System.out.println("currently active threads = " + count);
   }

   public void run() {
      System.out.println("This is run() method");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

This is run() method
currently active threads = 2
java_lang_thread.htm
廣告