【问题标题】:How to check if a thread was born?如何检查线程是否诞生?
【发布时间】:2014-12-11 11:57:16
【问题描述】:

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

在运行时,我按下启动MQTT_THREAD 的按钮,当我按下play 按钮时,它显示the thread MQTT_THREAD is not existing。我相信这主要是因为我不理解线程或逻辑中的一个小错误。下面是我的代码。

请看一看,让我知道我在想什么。

使用的 Code_utility 方法

public static Thread[] getAllRunninthreads() {
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    return threadArray;
}
public static boolean isThreadExist(String threadName) {
    boolean isExist = false;
    for (int i = 0; i < ThreadsUtility.getAllRunninthreads().length; i++) {
        if (ThreadsUtility.getAllRunninthreads()[i].getName().equals(threadName)) {
            return (isExist = true);
        }
    }
    return isExist;
}

代码_在主线程:

 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.");

             }
         }

【问题讨论】:

  • 你能在你创建和启动线程的地方添加一点代码吗?

标签: java android multithreading java.util.concurrent


【解决方案1】:

尝试只调用一次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;
}

这就是getAllStackTraces方法的api必须说的

 A zero-length array will be returned in the map value if the virtual machine has no stack trace information about a thread.

【讨论】:

  • 谢谢你的回答,但我的代码有什么问题
  • 好的,但是当我运行 ThreadsUtility.getAllRunninthreads();方法它给了我所有可用的线程,但我盯着的那个?是不是因为线程完成工作就终止了?
  • 是的,如果您的线程终止可能是正常的或某些异常,那么您肯定不会通过上面的代码看到它,因为上面的代码只是为了向您展示活动线程。
【解决方案2】:

Thread.getAllStackTraces().keySet(); 显示堆栈中的所有可用线程,但不显示已终止的线程。所以,我认为你的“mqtt 线程”可能不会做耗费时间的繁重工作,因此,当你按下“播放”按钮时,线程可能已经完成了它的工作,因此,TERMINATED 并且不会在@987654322 中列出@

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多