1. 程式人生 > 實用技巧 >Java中執行緒的生命週期和狀態

Java中執行緒的生命週期和狀態

1、執行緒在Java中,任何時間點都存在以下任何一種狀態

  1. New
  2. Runnable
  3. Blocked
  4. Waiting
  5. Timed Waiting
  6. Terminated

下圖顯示了執行緒在任何時刻的各種狀態。


2、執行緒的生命週期

    1. New(新執行緒):建立新執行緒時,它處於新狀態。當執行緒處於此狀態時,執行緒尚未開始執行。當一個執行緒處於新狀態時,它的程式碼還沒有執行,也沒有開始執行。
    2. Runnable(可執行狀態):準備執行的執行緒被移到可執行狀態。在這種狀態下,一個執行緒可能實際上正在執行,也可能隨時準備執行。執行緒排程程式負責為執行緒提供執行時間。
      多執行緒程式為每個執行緒分配固定的時間量。每個執行緒都會執行一段時間,然後暫停並將CPU交給另一個執行緒,這樣其他執行緒就有機會運行了。當這種情況發生時,所有準備好執行、等待CPU和當前正在執行的執行緒都處於可執行狀態。
Blocked/Waiting(阻塞/等待狀態):
      當執行緒暫時處於非活動狀態時,它將處於以下狀態之一:
      • Blocked
      • Waiting

例如,當執行緒等待I/O完成時,它處於阻塞狀態。執行緒排程程式負責重新啟用和排程阻塞/等待的執行緒。處於此狀態的執行緒在移到可執行狀態之前無法繼續執行。處於這些狀態的任何執行緒都不會佔用任何CPU週期。

當執行緒試圖訪問當前被其他執行緒鎖定的受保護程式碼部分時,該執行緒處於阻塞狀態。當受保護的部分被解鎖時,排程將選擇該部分被阻塞的執行緒之一,並將其移動到可執行狀態。當執行緒處於等待狀態時,它將等待另一個執行緒。當滿足此條件時,排程程式將得到通知,等待的執行緒將被移動到可執行狀態。

如果當前正在執行的執行緒被移到blocked/waiting狀態,則執行緒排程程式會安排另一個處於runnable狀態的執行緒執行。執行緒排程程式負

責確定要執行哪個執行緒。

  1. Timed Waiting(定時等待):當執行緒呼叫帶有超時引數的方法時,它處於定時等待狀態。執行緒處於這種狀態,直到超時完成或收到通知為止。例如,當一個執行緒呼叫sleep或conditional wait時,它將被移到一個timed waiting狀態。
  2. Terminated(終止狀態):執行緒因以下原因之一終止:
    • 因為它正常存在。當執行緒的程式碼完全由程式執行時,就會發生這種情況。
    • 因為發生了一些異常的錯誤事件,如分段錯誤或未處理的異常。

    處於終止狀態的執行緒不再消耗任何CPU週期。

3、用Java實現執行緒狀態

在Java中,要獲取執行緒的當前狀態,請使用Thread.getState()

方法獲取執行緒的當前狀態。Java提供java.lang.Thread.State類,該類定義執行緒狀態的列舉常量,其摘要如下:

1、常量型別:New

宣告:public static final Thread.State NEW

說明尚未啟動的執行緒的執行緒狀態。

2、常量型別:Runnable

宣告:public static final Thread.State RUNNABLE

說明:可執行執行緒的執行緒狀態。處於可執行狀態的執行緒正在Java虛擬機器中執行,但它可能正在等待來自作業系統(如處理器)的其他資源。

3、常量型別:Blocked

宣告:public static final Thread.State BLOCKED

說明:等待監視器鎖定時阻塞的執行緒的執行緒狀態。處於阻塞狀態的執行緒正在等待監視器鎖進入同步塊/方法,或在呼叫Object.wait()後重新輸入同步塊/方法。

4、常量型別:Waiting

宣告:public static final Thread.State WAITING

說明:由於呼叫以下方法之一使執行緒處於等待狀態:

Object.wait 不帶時間

Thread.join 不帶時間

LockSupport.park

處於等待狀態的執行緒正在等待另一個執行緒執行特定操作。

5、常量型別:Timed Waiting

宣告:public static final Thread.State TIMED_WAITING

說明:具有指定等待時間的等待執行緒的執行緒狀態。呼叫以下方法之一併且指定正等待時間讓執行緒處於定時等待狀態:

Thread.sleep 帶時間

Object.wait 帶時間

Thread.join 帶時間

LockSupport.parkNanos

LockSupport.parkUntil

6、常量型別:Terminated

宣告:public static final Thread.State TERMINATED

說明:終止執行緒的執行緒狀態。執行緒已完成執行。

// Java program to demonstrate thread states 
class thread implements Runnable 
{ 
    public void run() 
    { 
        // moving thread2 to timed waiting state 
        try
        { 
            Thread.sleep(1500); 
        }  
        catch (InterruptedException e)  
        { 
            e.printStackTrace(); 
        } 
          
        System.out.println("State of thread1 while it called join() method on thread2 -"+ 
            Test.thread1.getState()); 
        try
        { 
            Thread.sleep(200); 
        }  
        catch (InterruptedException e)  
        { 
            e.printStackTrace(); 
        }      
    } 
} 
  
public class Test implements Runnable 
{ 
    public static Thread thread1; 
    public static Test obj; 
      
    public static void main(String[] args) 
    { 
        obj = new Test(); 
        thread1 = new Thread(obj); 
          
        // thread1 created and is currently in the NEW state. 
        System.out.println("State of thread1 after creating it - " + thread1.getState()); 
        thread1.start(); 
          
        // thread1 moved to Runnable state 
        System.out.println("State of thread1 after calling .start() method on it - " +  
            thread1.getState()); 
    } 
      
    public void run() 
    { 
        thread myThread = new thread(); 
        Thread thread2 = new Thread(myThread); 
          
        // thread1 created and is currently in the NEW state. 
        System.out.println("State of thread2 after creating it - "+ thread2.getState()); 
        thread2.start(); 
          
        // thread2 moved to Runnable state 
        System.out.println("State of thread2 after calling .start() method on it - " +  
            thread2.getState()); 
          
        // moving thread1 to timed waiting state 
        try
        { 
            //moving thread1 to timed waiting state 
            Thread.sleep(200); 
        }  
        catch (InterruptedException e)  
        { 
            e.printStackTrace(); 
        } 
        System.out.println("State of thread2 after calling .sleep() method on it - "+  
            thread2.getState() ); 
          
          
        try 
        { 
            // waiting for thread2 to die 
            thread2.join(); 
        }  
        catch (InterruptedException e)  
        { 
            e.printStackTrace(); 
        } 
        System.out.println("State of thread2 when it has finished it's execution - " +  
            thread2.getState()); 
    } 
      
} 

輸出:

State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED

說明:建立新執行緒時,該執行緒處於新狀態。當對執行緒呼叫.start()方法時,執行緒排程程式會將其移到可執行狀態。每當對執行緒例項呼叫join()方法時,執行該語句的當前執行緒將等待該執行緒移動到終止狀態。因此,在控制檯上列印最後一條語句之前,程式在thread2上呼叫join(),使thread1等待thread2完成執行並移動到Terminated狀態。thread1進入Waiting狀態,因為它正在等待thread2完成它的執行,因為它在thread2上呼叫了join。