Java 如何检查线程是否已生成?

Java 如何检查线程是否已生成?,java,android,multithreading,java.util.concurrent,Java,Android,Multithreading,Java.util.concurrent,我创建了一个实用程序类,用于获取有关正在运行的线程的信息。一个名为MQTT_线程的线程在按下按钮时启动。我还有另一个名为play的按钮,当按下它时,它应该首先检查线程MQTT_线程是否存在,或者换句话说,是否出生 在运行时,我按下启动MQTTèu线程的按钮,当我按下play按钮时,显示线程MQTTèu线程不存在。我相信这是最重要的,因为我对线程的理解不够,或者逻辑上有一个小错误。下面是我的代码 请仔细看看,让我知道我错过了什么 使用的代码实用性方法 尝试只调用一次getAllRunninThre

我创建了一个实用程序类,用于获取有关正在运行的线程的信息。一个名为MQTT_线程的线程在按下按钮时启动。我还有另一个名为play的按钮,当按下它时,它应该首先检查线程MQTT_线程是否存在,或者换句话说,是否出生

在运行时,我按下启动MQTTèu线程的按钮,当我按下play按钮时,显示线程MQTTèu线程不存在。我相信这是最重要的,因为我对线程的理解不够,或者逻辑上有一个小错误。下面是我的代码

请仔细看看,让我知道我错过了什么

使用的代码实用性方法

尝试只调用一次getAllRunninThreads,因为一次又一次地调用它将不会为您提供一致的set/array值—想象一下创建新线程或退出线程会产生问题

public static boolean isThreadExist(String threadName) {
Thread[] threads = ThreadsUtility.getAllRunninthreads();
    for (int i = 0; i < threads.length; i++) {
        if (threads[i].getName().equals(threadName)) {
            return true;
        }
    }
    return false;
}

Thread.getAllStackTraces.keySet;显示堆栈中的所有可用线程,但不显示终止的线程。因此,我认为您的mqtt线程可能不会进行耗费时间的繁重工作,因此,当您按下play按钮时,线程可能已经完成了它的工作,因此,终止并且不会在线程中列出。getAllStackTraces.keySet

您可以为创建和启动线程的位置添加代码位吗?谢谢您的回答,但我的代码中有什么内容确定,但当我运行ThreadSutitility.getAllRunninthreads;方法它给了我所有的线索,除了我盯着的那条?这是因为线程在完成其工作时被终止吗?是的,如果您的线程被终止可能是正常的,或者是一些异常,那么您肯定无法通过上述代码看到它,因为上述代码只是为了向您显示活动线程。
 if (e.getSource() == Bplay) {
         if (!ThreadsUtility.isThreadExist(MQTT_THREAD)) {
             System.out.println(MQTT_THREAD + " is not existing.");
         }else {
             System.out.println(MQTT_THREAD + " exists.");
             if (!ThreadsUtility.isThreadExist(FILE_THREAD)) {
                 System.out.println(FILE_THREAD + " is not existing.");
             }else {
                 System.out.println(FILE_THREAD + " exists.");

             }
         }
public static boolean isThreadExist(String threadName) {
Thread[] threads = ThreadsUtility.getAllRunninthreads();
    for (int i = 0; i < threads.length; i++) {
        if (threads[i].getName().equals(threadName)) {
            return true;
        }
    }
    return false;
}
 A zero-length array will be returned in the map value if the virtual machine has no stack trace information about a thread.