Java : InterruptedException (割込み例外) - API使用例
InterruptedException (Java SE 18 & JDK 18) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。
概要
あるスレッドが待ち状態、休止状態、または占有されているとき、アクティビティの前かその間のいずれかにそのスレッドで割込みが発生した場合にスローされます。
スレッドA、スレッドBがあるとします。
スレッドAが待ち(wati)状態のときに、スレッドBからスレッドAに対して割り込み(interrupt)すると、スレッドAでInterruptedExceptionが発生して待ち状態が解除されます。
InterruptedExceptionが発生すると、割込みステータスはクリアされます。
その点はご注意ください。
final var thread = new Thread(() -> {
System.out.println("task start");
final var current = Thread.currentThread();
try {
System.out.println("isInterrupted 1 : " + current.isInterrupted());
// 割込み発生までループします。
while (!current.isInterrupted()) {
Thread.onSpinWait();
}
System.out.println("isInterrupted 2 : " + current.isInterrupted());
// 割込み発生中なので、sleepは即座にInterruptedExceptionを発生させます。
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException!");
System.out.println("isInterrupted 3 : " + current.isInterrupted());
} finally {
System.out.println("task end");
}
});
System.out.println("-- start --");
thread.start();
Thread.sleep(500);
thread.interrupt();
System.out.println("-- interrupt --");
thread.join();
System.out.println("-- join --");
// 結果
// ↓
//-- start --
//task start
//isInterrupted 1 : false
//-- interrupt --
//isInterrupted 2 : true
//InterruptedException!
//isInterrupted 3 : false
//task end
//-- join --
コンストラクタ
InterruptedException ()
詳細メッセージなしでInterruptedExceptionを構築します。
final var e = new InterruptedException();
System.out.println(e); // java.lang.InterruptedException
InterruptedException (String s)
指定された詳細メッセージを持つInterruptedExceptionを構築します。
final var e = new InterruptedException("abcd");
System.out.println(e); // java.lang.InterruptedException: abcd
Throwableで宣言されたメソッド
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
「Java API 使用例 : Throwable」をご参照ください。
関連記事
スレッド関連
- API 使用例
- Callable
- CancellationException
- ConcurrentHashMap.KeySetView (並列処理用セット)
- ConcurrentMap (並列処理用マップ)
- ConcurrentModificationException (並列処理例外)
- Condition (同期)
- CopyOnWriteArrayList (並列処理用リスト)
- CopyOnWriteArraySet (並列処理用セット)
- CountDownLatch (同期)
- CyclicBarrier (同期)
- Exchanger (同期)
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- Lock (同期)
- Object (オブジェクト)
- Runnable
- Semaphore (セマフォ)
- Thread (スレッド)
- TimeUnit
例外関連
- API 使用例
- Error (エラー)
- Exception(チェック例外)
- RuntimeException(非チェック例外)
- ArithmeticException (算術例外)
- CancellationException
- ClassCastException (キャスト例外)
- ConcurrentModificationException (並列処理例外)
- DateTimeException (日付・時刻の例外)
- DateTimeParseException (日付・時刻の解析例外)
- IllegalArgumentException
- IllegalStateException
- IndexOutOfBoundsException
- NullPointerException
- UnsupportedOperationException
- Throwable