Java

java怎么判断线程是否结束

小亿
193
2023-11-29 21:16:23
栏目: 编程语言

在Java中,可以通过以下几种方法判断线程是否结束:

  1. 使用Thread.isAlive()方法,该方法返回一个布尔值,表示线程是否还活着。如果线程已经终止或者还未启动,则返回false,否则返回true。
Thread thread = new Thread();
thread.start();

if (thread.isAlive()) {
    System.out.println("线程还在运行");
} else {
    System.out.println("线程已经结束");
}
  1. 使用Thread.join()方法,该方法会阻塞当前线程,直到目标线程执行完毕。
Thread thread = new Thread();
thread.start();

try {
    thread.join();
    System.out.println("线程已经结束");
} catch (InterruptedException e) {
    e.printStackTrace();
}
  1. 使用Thread.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("线程已经结束");
}

以上是几种常用的判断线程是否结束的方法,根据实际情况可以选择适合的方法来判断线程的状态。

0
看了该问题的人还看了