Java Thread enumerate() 方法



描述

Java Thread enumerate() 方法將當前執行緒的執行緒組及其子組中的每個活動執行緒複製到指定的陣列中。它使用tarray引數呼叫當前執行緒的執行緒組的 enumerate 方法。

宣告

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

public static int enumerate(Thread[] tarray)

引數

tarray − 這是一個要複製到的 Thread 物件陣列。

返回值

此方法返回放入陣列中的執行緒數

異常

SecurityException − 如果存在安全管理器並且其 checkAccess 方法不允許該操作。

示例:在單執行緒環境中建立執行緒陣列

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

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
     
      // 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,5,main]
currently active threads = 1
0: Thread[Admin Thread,5,main]

示例:在多執行緒程式中獲取執行緒陣列

以下示例顯示了 Java Thread activeCount() 方法的使用。在此程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,使用 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);
	  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]);
      }
   }

   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
0: Thread[#1,main,5,main]
1: null
java_lang_thread.htm
廣告

© . All rights reserved.