Javaでスレッドの終了を確認する方法
Javaでは、スレッドが終了しているかどうかを主に以下の方法で判定します
- スレッドが実行中かどうか
Thread thread = new Thread();
thread.start();
if (thread.isAlive()) {
System.out.println("线程还在运行");
} else {
System.out.println("线程已经结束");
}
- スレッドを結合する
Thread thread = new Thread();
thread.start();
try {
thread.join();
System.out.println("线程已经结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
- スレッド.getState()
- スレッドはまだ開始されていません
- 実行中: スレッドは実行されています
- 終了:スレッドが終了しました
Thread thread = new Thread();
thread.start();
Thread.State state = thread.getState();
if (state == Thread.State.RUNNABLE) {
System.out.println("线程正在运行");
} else if (state == Thread.State.TERMINATED) {
System.out.println("线程已经结束");
}
スレッドが終了したかを判別する一般的な方法が上で示されており、実際の状況に基づいてスレッドの状態を判断するために適切な方法が選択できます。