【问题标题】:In Java, how do you determine if a thread is running?在 Java 中,如何确定线程是否正在运行?
【发布时间】:2010-10-26 01:41:12
【问题描述】:

如何判断一个线程是否正在运行?

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    Thread.isAlive()

    【讨论】:

    • 我猜它和Thread.State.RUNNABLE有些不同(最后一个似乎更可靠)
    【解决方案2】:

    你可以使用这个方法:

    boolean isAlive()
    

    如果线程还活着则返回true,如果线程死了则返回false。 这不是静态的。您需要对 Thread 类的对象的引用。

    另一个提示: 如果您正在检查它的状态以使主线程在新线程仍在运行时等待,您可以使用 join() 方法。更方便。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          准确地说,

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

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

          【讨论】:

            【解决方案6】:

            Thread.State 枚举类和新的 getState() API 用于查询线程的执行状态。

            一个线程在给定的时间点只能处于一种状态。这些状态是不反映任何操作系统线程状态的虚拟机状态 [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED]。

            枚举Thread.State扩展枚举实现SerializableComparable

            • getState()jdk5 - public State getState() {...} « 返回this线程的状态。此方法设计用于监控系统状态,而不是用于同步控制。

            • isAlive() - public final native boolean isAlive(); « 如果调用它的线程仍然存在,则返回 true活着,否则返回 false。如果线程已启动且尚未死亡,则线程处于活动状态。

            java.lang.Threadsun.misc.VM 类的示例源代码。

            package java.lang;
            public class Thread implements Runnable {
                public final native boolean isAlive();
            
                // Java thread status value zero corresponds to state "NEW" - 'not yet started'.
                private volatile int threadStatus = 0;
            
                public enum State {
                    NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
                }
            
                public State getState() {
                    return sun.misc.VM.toThreadState(threadStatus);
                }
            }
            
            package sun.misc;
            public class VM {
                // ...
                public static Thread.State toThreadState(int threadStatus) {
                    if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
                        return Thread.State.RUNNABLE;
                    } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
                        return Thread.State.BLOCKED;
                    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
                        return Thread.State.WAITING;
                    } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
                        return Thread.State.TIMED_WAITING;
                    } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
                        return Thread.State.TERMINATED;
                    } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
                        return Thread.State.NEW;
                    } else {
                        return Thread.State.RUNNABLE;
                    }
                }
            }
            

            Examplejava.util.concurrent.CountDownLatch并行执行多个线程,完成所有线程后主线程执行。 (直到并行线程完成他们的任务主线程将被阻塞。)

            public class MainThread_Wait_TillWorkerThreadsComplete {
                public static void main(String[] args) throws InterruptedException {
                    System.out.println("Main Thread Started...");
                    // countDown() should be called 4 time to make count 0. So, that await() will release the blocking threads.
                    int latchGroupCount = 4;
                    CountDownLatch latch = new CountDownLatch(latchGroupCount);
                    new Thread(new Task(2, latch), "T1").start();
                    new Thread(new Task(7, latch), "T2").start();
                    new Thread(new Task(5, latch), "T3").start();
                    new Thread(new Task(4, latch), "T4").start();
            
                    //latch.countDown(); // Decrements the count of the latch group.
            
                    // await() method block until the current count reaches to zero
                    latch.await(); // block until latchGroupCount is 0
                    System.out.println("Main Thread completed.");
                }
            }
            class Task extends Thread {
                CountDownLatch latch;
                int iterations = 10;
                public Task(int iterations, CountDownLatch latch) {
                    this.iterations = iterations;
                    this.latch = latch;
                }
                @Override
                public void run() {
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName + " : Started Task...");
                    for (int i = 0; i < iterations; i++) {
                        System.out.println(threadName + " : "+ i);
                        sleep(1);
                    }
                    System.out.println(threadName + " : Completed Task");
                    latch.countDown(); // Decrements the count of the latch,
                }
                public void sleep(int sec) {
                    try {
                        Thread.sleep(1000 * sec);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            

            @另见

            【讨论】:

            • A thread is alive if it has been started and has not yet died。死了是什么意思?状态是TERMINATED?
            【解决方案7】:

            让你的线程在完成时通知其他线程。这样您就可以始终准确地知道发生了什么。

            【讨论】:

              【解决方案8】:

              想写一段代码来演示 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());
                  }
              
              
              }
              

              【讨论】:

                【解决方案9】:

                您可以使用:Thread.currentThread().isAlive();。如果此线程处于活动状态,则返回 truefalse 否则。

                【讨论】:

                • 这不会总是返回 true 吗?我认为它必须是另一个线程的句柄。毕竟,当前线程不是正在执行Thread.currentThread().isAlive(),因此总是返回true吗?
                【解决方案10】:

                使用Thread.currentThread().isAlive()查看线程是否存活[输出应该为真]这意味着线程仍在运行内部的代码run() 方法或使用 Thread.currentThread.getState() 方法获取线程的确切状态

                【讨论】:

                  猜你喜欢
                  • 2012-09-17
                  • 2010-12-08
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2023-03-09
                  • 2023-03-14
                  • 2015-04-02
                  • 1970-01-01
                  相关资源
                  最近更新 更多