我正在实施Android“服务”。在其“onCreate”中,我想开始并等待另一个线程的完成。 ClientServiceLoop是run()中带有while(true)循环的Runnable,具有简单的返回条件。Android线程:是否需要等待线程在“加入”之前启动?
@Override
public void onCreate() {
super.onCreate();
mClientServiceLoopThread = new Thread(mClientServiceLoop = new ClientServiceLoop(),
"ClientServiceLoop");
mClientServiceLoopThread.start();
try {
mClientServiceLoopThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我想知道是,以后我叫start()方法,是保证已经呼吁Runnable的run()方法已经是新生成的线程?我应该在调用join()之前等待线程启动吗?我无法找到有关确切地址保证的文件。
对此进行测试,如果我不调用start(),join()会立即返回。我想知道的是何时isAlive()被实际设置。我搜索了Android SDK,但无法找到nativePeer设置的位置。
-
mClientServiceLoopThread = new Thread(mClientServiceLoop = new ClientServiceLoop(),
"ClientServiceLoop");
boolean b = mClientServiceLoopThread.isAlive(); // false
try {
mClientServiceLoopThread.join(); // internally just while(isAlive)...so returns immediately
} catch (InterruptedException e) {
e.printStackTrace();
}
mClientServiceLoopThread.start();//FIXME TESTING ONLY
- Android的源
/**
* Blocks the current Thread (<code>Thread.currentThread()</code>) until
* the receiver finishes its execution and dies.
*
* @throws InterruptedException if the current thread has been interrupted.
* The interrupted status of the current thread will be cleared before the exception is
* thrown.
* @see Object#notifyAll
* @see java.lang.ThreadDeath
*/
public final void join() throws InterruptedException {
synchronized (lock) {
while (isAlive()) {
lock.wait();
}
}
}
/**
* Returns <code>true</code> if the receiver has already been started and
* still runs code (hasn't died yet). Returns <code>false</code> either if
* the receiver hasn't been started yet or if it has already started and run
* to completion and died.
*
* @return a <code>boolean</code> indicating the liveness of the Thread
* @see Thread#start
*/
public final boolean isAlive() {
return (nativePeer != 0);
}
其中是nativePeer设置??
好吧,无论答案是有意义的。谢谢! –