【发布时间】:2015-11-21 05:54:16
【问题描述】:
我正在实现一个 Android“服务”。在它的“onCreate”中,我想启动并等待另一个线程的完成。 ClientServiceLoop 是一个 Runnable,在 run() 中有一个 while(true) 循环,返回条件很简单。
@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
-- 安卓源码
/**
* 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 设置在哪里??
【问题讨论】:
标签: android multithreading runnable