有没有办法检查一个Thread对象是否已经调用了start方法?
我想实现这样的功能:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
如果线程尚未运行,则启动线程。
有没有办法检查一个Thread对象是否已经调用了start方法?
我想实现这样的功能:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
如果线程尚未运行,则启动线程。
rt
是一个线程(Thread
),只需检查 rt.isAlive()
。rt.isAlive()
。我曾成功地使用过这种方法:
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
通过传递一个线程来调用此方法。它将每500毫秒检查一次线程是否存活,起始延迟为500毫秒(您可以使用自定义值)。我经常使用这种方法。
void threadAliveChecker(final Thread thread) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (!thread.isAlive()) {
// do your work after thread finish
runOnUiThread(new Runnable() {
@Override
public void run() {
// do the ui work here
}
});
timer.cancel();
}else {
// do work when thread is running like show progress bar
}
}
}, 500, 500); // first is delay, second is period
}
例子:
Thread thread = new Thread(myRunnable);
thread.start();
threadIsAliveChecker(thread);
这个方法将会让我们知道线程何时完成它的工作。
run
方法中设置一个 bool 值,有一个短暂的时间段,在这个时间段内你已经启动了线程,但 bool 值还没有被设置为 true。这就是为什么我建议在主线程中设置它的原因。 - EboMike