在Java中,你如何确定一个线程是否正在运行?

你如何确定线程是否正在运行?

Thread.isAlive()

你可以使用这个方法:

 boolean isAlive() 

如果线程仍然活着,则返回true;如果线程已经死亡,则返回false。 这不是静态的。 您需要对Thread类的对象进行引用。

还有一点提示:如果你正在检查它的状态,以使主线程在新线程仍在运行的时候等待,你可以使用join()方法。 这是更方便。

我想你可以使用GetState() ; 它可以返回一个线程的确切状态。

通过调用Thread.isAlive检查线程状态。

当你的线程完成时通知其他线程。 这样你总能知道到底发生了什么。

准确地说,

如果线程已经启动(可能还没有运行)但尚未完成其运行方法,则Thread.isAlive()返回true。

Thread.getState()返回线程的确切状态。

想到编写一个代码来演示isAlive(),getState()方法,这个例子监视一个线程仍然终止(死亡)。

 package Threads; import java.util.concurrent.TimeUnit; public class ThreadRunning { static class MyRunnable implements Runnable { private void method1() { for(int i=0;i<3;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} method2(); } System.out.println("Existing Method1"); } private void method2() { for(int i=0;i<2;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} method3(); } System.out.println("Existing Method2"); } private void method3() { for(int i=0;i<1;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} } System.out.println("Existing Method3"); } public void run(){ method1(); } } public static void main(String[] args) { MyRunnable runMe=new MyRunnable(); Thread aThread=new Thread(runMe,"Thread A"); aThread.start(); monitorThread(aThread); } public static void monitorThread(Thread monitorMe) { while(monitorMe.isAlive()) { try{ StackTraceElement[] threadStacktrace=monitorMe.getStackTrace(); System.out.println(monitorMe.getName() +" is Alive and it's state ="+monitorMe.getState()+" || Execution is in method : ("+threadStacktrace[0].getClassName()+"::"+threadStacktrace[0].getMethodName()+") @line"+threadStacktrace[0].getLineNumber()); TimeUnit.MILLISECONDS.sleep(700); }catch(Exception ex){} /* since threadStacktrace may be empty upon reference since Thread A may be terminated after the monitorMe.getStackTrace(); call*/ } System.out.println(monitorMe.getName()+" is dead and its state ="+monitorMe.getState()); } }