如何在Java中臨時掛起執行緒?


執行緒是Java程式的重要組成部分。它們也被稱為輕量級程序。每個Java程式至少都有一個主執行緒。它們在同時執行多個任務方面發揮著非常重要的作用。它們在後臺執行,不會影響主程式的執行。同時使用多個執行緒稱為多執行緒。

執行緒的狀態

執行緒可以存在於以下任何一種狀態中。它從建立到銷燬具有完整的生命週期。執行緒生命週期狀態如下:

  • 新建 - 這是建立執行緒的第一個階段。它尚未執行。

  • 可執行 - 這是執行緒正在執行或準備執行的狀態。

  • 阻塞/等待 - 這是執行緒正在等待資源並且處於非活動狀態。

  • 掛起 - 這是執行緒暫時處於非活動狀態。

  • 終止 - 這是執行緒已停止執行的狀態。

在Java中臨時掛起執行緒

如果要掛起執行緒,則該執行緒必須處於掛起狀態。在這種狀態下,執行緒暫時掛起,即處於非活動狀態。`suspend()`方法用於暫時掛起執行緒。它將保持掛起狀態,直到程式恢復為止。我們可以透過`resume()`方法恢復掛起的執行緒。

語法

public final void suspend()

`suspend()`方法是一個最終方法,這意味著它不能被子類重寫。此外,由於返回資料型別是void,它不會向用戶返回任何值。該方法是公共的。

`suspend()`方法會暫時停止執行緒,直到對其呼叫`resume()`方法為止。

示例

以下是如何使用`suspend()`方法在Java中暫時掛起執行緒的示例。

import java.io.*;
public class Main extends Thread {
   public void run()
   {
      try {
      //print the current thread
         System.out.println("Current thread is thread number " + Thread.currentThread().getName());
      }
      catch (Exception e) {
         System.out.println(e);
      }
   }

   public static void main(String[] args) throws Exception
   {

      //1 thread created
      Main t1=new Main();

      //running the threads
      t1.start();

      //putting it to sleep for 3ms
      t1.sleep(300);

      //now suspend the thread 
      t1.suspend();
      System.out.println("Thread is suspended");

      //resume the thread
      t1.resume();
      
      System.out.println("Thread is Resumed");
   }
}

輸出

以下是上述程式碼的輸出

Current thread is thread number Thread-0
Thread is suspended
Thread is Resumed

解釋

在上述程式碼中,我們建立了一個執行緒。我們執行該執行緒,然後讓它休眠3毫秒。然後,為了暫時掛起執行緒,我們使用了`suspend()`方法。它會暫時停止該執行緒的執行。稍後,該執行緒將透過`resume()`方法恢復。

因此,我們可以得出結論,`suspend()`方法可用於在Java中暫時掛起執行緒。儘管此方法已棄用,但建議瞭解死鎖的後果並使用它。

更新於:2023年7月24日

817 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告