首頁 > Java > java教程 > 主體

Java 中斷異常

WBOY
發布: 2024-08-30 16:15:01
原創
894 人瀏覽過

當執行緒在執行某些活動之前或執行時可能正在休眠、等待或被佔用和中斷時,會發生 InterruptedException。有時,方法可能想要測試目前執行緒是否已中斷。如果它被中斷,那麼它將立即拋出異常。否則,它將按照原來的方式工作。在本主題中,我們將學習 Java InterruptedException。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

文法

為了使用異常,您必須使用以下語法:

if (Thread.interrupted ())  // Clears interrupted status!
throw new InterruptedException ();
登入後複製

這裡InterruptedException()方法建立了一個InterruptedException,其中沒有詳細訊息作為參數。

但如果它像 InterruptedException (String s) 一樣拋出,它會建立一個帶有一些特定細節的 InterruptedException。在此方法中,s 是詳細訊息。

InterruptedException 在 Java 中如何運作?

這裡我們討論InterruptedException的工作流程。在多執行緒程式碼中,執行緒經常會阻塞;執行緒暫停執行,直到滿足某些外部條件,例如:

  • 當鎖被釋放時
  • 或另一個執行緒完成操作
  • 並且一些 I/O 操作完成

在這裡,線程可以被中斷。當中斷發生時,它會阻止執行緒執行它們正在執行的常規工作。但對指定中斷的確切回應取決於執行緒的狀態以及執行緒的實作方式,如下所示:

我們將有一個線程,可用於阻止線程或較早存在的線程。當它被捕獲時,它會拋出 InterruptedException。如果沒有問題並且沒有較早的線程,則該線程將繼續其工作。當線程遇到異常時,它將線程的中斷狀態設為 true。執行緒會定期輪詢方法checkInterrupted()。這是線程預期工作的首選方式。過程完成後,就會發生清理活動。清理完畢後,停止執行。如果有的話,它會拋出 InterruptedException,如果沒有,它會繼續正常的執行流程。

如果上述過程中出現中斷,該過程不應該立即關閉執行緒。這是因為它將處於某些計算的中間,而計算總是會發生,因此它必須等待。

建構子

建構子是 Java 對象,有助於初始化新建立的對像或方法。它是一個沒有任何回傳類型的 Java 實例。由於這應該初始化對象,因此它與其所屬的類別具有相同的名稱。因此,每當呼叫該物件時,都會自動呼叫建構函式並進行初始化。下面是一個構造方法。

InterruptedException ()
登入後複製

這裡,這個方法創造了一個沒有訊息的異常。此處正在建立 InterruptedException 類別的實例。在此建構函式中,訊息參數被設定為 null。

範例:

public InterruptedException () InterruptedException (String s)
登入後複製

在InterruptedException類別的這個方法中,參數被用來當作字串格式的指定訊息。這裡的字串參數解釋了引發錯誤的類別的名稱。

InterruptedException 範例

現在我們將看一個執行緒被中斷的範例:

// Java Program to check how
// interrupt () method  works
// simultaneously while a thread stops working
class CheckInterruption extends Thread {
public void run ()
{
try {
Thread.sleep (2000);
System.out.println ( "We are checking Interrupted Exception");
}
catch (InterruptedException e) {
throw new RuntimeException ( "Thread is" + "interrupted");
}
}
public static void main (String args[])
{
CheckInterruption t1 = new CheckInterruption ();
t1.start ();
try {
t1.interrupt ();
}
catch (Exception e) {
System.out.println ("Exception handled");
}
}
}
登入後複製

輸出:

Java 中斷異常

上面的程式碼幫助我們理解中斷異常的概念。我們有一個類,CheckInterruption,它擴充了 Java 的 Thread 類別。然後它在 try 區塊中尋找異常。如果存在異常,則會在 catch 區塊中擷取該異常,並將輸出顯示為 catch 區塊。在我們的範例中就是這種情況,捕獲了中斷,並顯示了必要的輸出。但程式並未完成,因為 catch 區塊呼叫了 Java 中存在的 Exception() 方法。現在讓我們檢查一個範例,其中捕獲了異常,然後啟動下一個執行緒。

class CheckInterruptingThread2 extends Thread{
public void run (){
try{  Thread.sleep (1000);
System.out.println ("task");
}catch (InterruptedException e){
System.out.println ("Exception is handled "+e);  }
System.out.println ("thread is now in running state...");
}
public static void main (String args[]){
CheckInterruptingThread2 t1=new CheckInterruptingThread2 ();
t1.start ();
t1.interrupt ();
}
}
登入後複製

輸出:

Java 中斷異常

The above program uses a class that is again extending the Thread class in Java. In the try () block, we make the thread sleep for some time, and then the catch block catches the exception when it is encountered. Once it is handled, the message is printed, and then the interrupt () method is called, after which the next thread moves to the running state. The same is displayed after the method call is finished and the thread starts working.

How to avoid InterruptedException?

The solution to this exception is you can stop making use of thread.sleep () method. Instead of this method, the more efficient method will be SystemClock.sleep () method. Another replacement for the above-mentioned method can be using TimeCOunter, which will depend on the logic and code where it is being used. This can also be an optimal solution.

If at all you would still like to make use of thread.sleep () then it should be used as below.

try {
Thread.sleep ();
} catch (InterruptedException e) {
Thread.currentThread ().interrupt (); /* this line will see to it that Thread.interrupted () always returns true */
throw new RuntimeException (e);
}
登入後複製

Conclusion – Java InterruptedException

As the word exception suggests, it is a state which can be checked and allowed to pass in some cases. InterruptedException happens when a thread waits or sleeps, and other threads are interrupted and cannot proceed further. We can handle this exception by either using proper try-catch blocks or by avoiding the usage of the sleep () method.

以上是Java 中斷異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!