Java Thread getState()方法

2019-10-16 22:24:47

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

語法

public Thread.State getState()

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

範例

public class JavaGetStateExp implements Runnable   
{  
   public void run()   
    {  
        // returns the state of the thread  
        Thread.State state = Thread.currentThread().getState();  
        System.out.println("Running thread name: "+ Thread.currentThread().getName());  
        System.out.println("State of thread: " + state);  
    }  
    public static void main(String args[])   
    {  
        JavaGetStateExp g = new JavaGetStateExp();  
        Thread t1= new Thread(g);   
        Thread t2= new Thread(g);   
        // call run() function  
        t1.start();     
        t2.start();  
    }  
}

執行上面範例程式碼,得到以下結果:

Running thread name: Thread-0
State of thread: RUNNABLE
Running thread name: Thread-1
State of thread: RUNNABLE