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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/861346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:20:39  来源:igfitidea点击:

In Java, how do you determine if a thread is running?

javamultithreading

提问by

How do you determine if a thread is running?

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

回答by Wayne

Thread.isAlive()

Thread.isAlive()

回答by Wayne

Check the thread status by calling Thread.isAlive.

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

回答by Chathuranga Chandrasekara

I think you can use GetState(); It can return the exact state of a thread.

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

回答by Abdulsattar Mohammed

You can use this method:

您可以使用此方法:

boolean isAlive()

It returns true if the thread is still alive and false if the Thread is dead. This is not static. You need a reference to the object of the Thread class.

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

One more tip: If you're checking it's status to make the main thread wait while the new thread is still running, you may use join() method. It is more handy.

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

回答by Bombe

Have your thread notify some other thread when it's finished. This way you'll always know exactly what's going on.

让您的线程在完成时通知其他线程。这样,您将始终确切地知道发生了什么。

回答by sxnamit

To be precise,

准确地说,

Thread.isAlive()returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

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

Thread.getState()returns the exact state of the thread.

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

回答by Roshan

Thought to write a code to demonstrate the isAlive() , getState()methods, this example monitors a thread still it terminates(dies).

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


}

回答by Yash

Thread.Stateenum class and the new getState()API are provided for querying the execution state of a thread.

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

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states[NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED].

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

enum Thread.Stateextends Enum implements Serializable, Comparable

enum Thread.State扩展了 Enum 实现了Serializable, Comparable

  • getState()jdk5- public State getState() {...}?Returns the state of thisthread. This method is designed for use in monitoring of the system state, not for synchronization control.

  • isAlive()- public final native boolean isAlive();?Returns trueif the thread upon which it is called is still alive, otherwise it returns false. A thread is alive if it has been started and has not yet died.

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

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

Sample Source Code's of classes java.lang.Threadand sun.misc.VM.

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;
        }
    }
}


Examplewith java.util.concurrent.CountDownLatchto execute multiple threads parallel, After completing all threads main thread execute. (until parallel threads complete their task main thread will be blocked.)

实施例java.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();
        }
    }
}

@See also

@也可以看看