Java Thread getState() 方法



描述

Java Thread getState() 方法返回此執行緒的狀態。它旨在用於監視系統狀態,而不是用於同步控制。

宣告

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

public Thread.State getState()

引數

返回值

此方法返回此執行緒的狀態。

異常

示例:獲取使用 Runnable 介面建立的執行緒的狀態

以下示例演示了 Java Thread getState() 方法的用法。在這個程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在 run() 方法中,使用 getState() 方法列印當前執行緒的狀態。在 main 方法中,我們建立了 ThreadDemo 執行緒,並使用 start() 方法啟動此執行緒。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {

      // returns the state of this thread
      Thread.State state = Thread.currentThread().getState();
      System.out.println(Thread.currentThread().getName());
      System.out.println("state = " + state);
   }

   public static void main(String args[]) {
      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();   
   }
} 

輸出

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

Thread-0
state = RUNNABLE

示例:獲取使用 Thread 類建立的執行緒的狀態

以下示例演示了 Java Thread getState() 方法的用法。在這個程式中,我們透過擴充套件 Thread 類建立了一個執行緒類 ThreadDemo。在 run() 方法中,使用 getState() 方法列印當前執行緒的狀態。在 main 方法中,我們建立了 ThreadDemo 執行緒,並使用 start() 方法啟動此執行緒。

package com.tutorialspoint;

public class ThreadDemo extends Thread {

   public void run() {

      // returns the state of this thread
      Thread.State state = Thread.currentThread().getState();
      System.out.println(Thread.currentThread().getName());
      System.out.println("state = " + state);
   }

   public static void main(String args[]) {
      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();   
   }
} 

輸出

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

Thread-1
state = RUNNABLE
java_lang_thread.htm
廣告