在我的线程中,我应该每隔一秒钟就做一件事。例如:让x=3,它应该在秒1, 4, 7, ...做那件事。
将线程wait()设置为x秒是做不到的--因为它可能会被中断,以便在x第二阶段执行其他事情,因此无法跟踪它应该以的方式之间传递的时间。因此,线程应该想出一种有效的方法,让自己知道x秒已经在时钟上传递了。
有效的方法是什么?
我现在唯一的方法是继续检查系统时钟,以确定它是第二个1,还是4,还是7,即第二个i,其中有i%3==1。然而,这太浪费了,没有任何好处。
做这件事最好的方法是什么?
蒂娅。
//=
编辑:
我认为这将是一种查找系统时钟并在每隔一段时间打断我的方法。
Java有这样的方法吗?
发布于 2014-10-10 00:12:54
我不知道你想做什么--像这样吗?
boolean interrupted;
long endWait = System.currentTimeMillis() + 3000; // or 1000 * x
do {
interrupted = false;
long timeRemaining = endWait - System.currentTimeMillis();
if (timeRemaining <= 0) {
break;
}
try {
Thread.sleep(timeRemaining);
} catch (InterruptedException e) {
... what you need to do when interrupted
interrupted = true;
}
} while (interrupted);https://stackoverflow.com/questions/26289879
复制相似问题