我在当前的android instrumentation测试中存在litte竞态条件。我要的是:如何等待java中的线程启动
- T1:启动线程T2
- T2做点事
- T1:与T2
加入对于步骤1和3是Android的使用生命周期事件。但由于仪器测试一切都发生得非常快,我得到:
- T1:启动线程T2
- T1:与T2(它变成是一个空操作)
- T2加入做点事
当然,我可以添加一些睡眠,以获得所需的行为,但我不知道是否有更好的方法来做到这一点。即有没有办法确保只有start()
-ed的线程确实启动的好,并且还没有坐在某个调度队列中等待启动。
(安迪的男孩,我怀念阿达基于交会多任务)
并回答垫的问题:
if (this.thread != null && this.thread.isAlive())
{
this.stop.set (true);
try
{
this.thread.join (1000);
}
catch (final InterruptedException Exception)
{
android.util.Log.w (Actor.TAG, "Thread did not want to join.", Exception);
} // try
} // if
正如我所说的:无操作时,因为线程尚未启动。
不会使敏感'Thread.join()'等待连接的线程死掉(除非你设置一个很短的超时)。你确定这个错误不是其他的吗? – Mat 2011-04-24 14:56:04
问题不在于单元测试的速度 - 这是线程调度正在进行的方式。 – jefflunt 2011-04-24 15:09:06
@Mat:我添加了一个代码示例来回答这个问题。 – Martin 2011-04-24 15:19:15