Java 中断例外

WBOY
リリース: 2024-08-30 16:15:01
オリジナル
894 人が閲覧しました

InterruptedException は、スレッドがスリープ中、待機中、または占有されていて、何らかのアクティビティの実行前または実行時に中断された場合に発生します。メソッドでは、現在のスレッドが中断されたかどうかをテストする必要がある場合があります。中断された場合は、すぐに例外がスローされます。それ以外の場合は、以前と同じように動作します。このトピックでは、Java InterruptedException について学習します。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

構文

例外を使用するには、次の構文を使用する必要があります:

if (Thread.interrupted ())  // Clears interrupted status!
throw new InterruptedException ();
ログイン後にコピー

ここで、メソッド InterruptedException () は、パラメータとして詳細メッセージを含まない InterruptedException を作成します。

ただし、InterruptedException (String s) のようにスローされた場合は、特定の詳細を含む InterruptedException が作成されます。このメソッドでは、s は詳細メッセージです。

Java では InterruptedException はどのように機能しますか?

ここでは、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 中断例外

上記のコードは、中断例外の概念を理解するのに役立ちます。 Java の Thread クラスを拡張するクラス CheckInterruption があります。次に、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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!