Java 如何检查Android线程是否正在运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4348438/
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-14 16:20:10  来源:igfitidea点击:

How to check if an Android Thread is running

javaandroidmultithreading

提问by wajiw

Is there a way to check if a Thread object has had start called on it already?

有没有办法检查一个 Thread 对象是否已经开始调用它?

I'm trying to so something like:

我正在尝试这样的事情:

if(rt.isAlive() == true)
{
    Log.v(TAG, "START RECORD");
    rt.recording = true;
}
else
{
    Log.v(TAG, "START THREAD/RECORD");

    rt.start();
}

where it would start the thread if it's not already running.

如果它尚未运行,它将在哪里启动线程。

采纳答案by EboMike

Assuming that rtis a Thread, just check rt.isAlive().

假设这rt是一个Thread,只需检查rt.isAlive().

Alternatively, just use a boolean flag and set it to true right before you start your thread.

或者,只需在开始线程之前使用布尔标志并将其设置为 true。

I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice - there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a "false" negative on rt.isAlive().

我实际上更喜欢布尔方法,因此主线程无法两次启动另一个线程 - 在您的线程启动并运行之前可能会有很短的延迟,并且如果您的主线程尝试快速启动线程两次继承,它可能会在 上得到“假”否定rt.isAlive()

回答by Eric Levine

If you called start on it, and it is running, you will get an IllegalThreadStateException. Catching that is one way to know.

如果你调用 start 并且它正在运行,你会得到一个IllegalThreadStateException. 捕捉这是一种了解方式。

Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start().

另一种选择是扩展 Thread 并添加一个布尔值,您可以在其中跟踪您的 Thread 是否已启动。您可以覆盖 Thread 的 start 方法以在调用之前检查布尔值super.start()

You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.

不过,在 Android 中使用线程时应该非常小心。确保您了解启动它的组件的生命周期。此外,您应该考虑使用一些辅助类,例如 Handler 和 AsyncTask,而不是直接生成线程。

回答by j2emanue

I've used this approach with success:

我成功地使用了这种方法:

if ( mythread.getState() == Thead.State.NEW )
    //then we have a brand new thread not started yet, lets start it
    mythread.start();
else
    //it is running already compensate