12. shutdown.shutdowmnow
shutdown()
shutdown() は
「新しい仕事は受け付けない」 「今動いている仕事は最後までやる」
です。
⸻
shutdown() サンプル
Java
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
scheduler.execute(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("処理中 " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("処理終了");
});
Thread.sleep(2000);
System.out.println("shutdown 実行");
scheduler.shutdown();
System.out.println("main終了");
}
}
⸻
実行イメージ
⸻
ポイント
shutdown後も、
既に動いているタスク
は継続されます。
⸻
shutdownNow()
shutdownNow() は
「今すぐ止めろ」
です。
内部的には:
interrupt()
を送ります。
⸻
shutdownNow() サンプル
Text Only
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
scheduler.execute(() -> {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("処理中 " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("割り込み発生");
}
System.out.println("タスク終了");
});
Thread.sleep(3000);
System.out.println("shutdownNow 実行");
scheduler.shutdownNow();
System.out.println("main終了");
}
}
⸻
実行イメージ
⸻
interrupt の重要性
shutdownNow() は
絶対停止
ではありません。
スレッド側が:
を処理しないと止まりません。
⸻
interruptを無視すると?
だと止まりにくくなります。
⸻
Java Gold 的重要ポイント
| 関数 | 動作 |
|---|---|
| shutdown() | 安全停止 |
| shutdownNow() | 強制停止要求 |
⸻
よく出る問題
shutdown後
すると:
⸻
サンプル
↓
⸻
終了待ち。
意味:
最大10秒待つ
⸻
実務でよくある形
Java
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(
5,
TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
}
⸻
図でイメージ
⸻
shutdownNow()