在Java中运行代码x秒钟? [英] Run code for x seconds in Java?
问题描述
我想编写一个Java while循环,该循环将迭代15秒.我想到的一种方法是存储当前系统时间+ 15秒,然后将其与while循环签名中的当前时间进行比较.
I'd like to write a java while loop that will iterate for 15 seconds. One way I thought to do this would be to store the current system time + 15sec and then compare that to the current time in the while loop signature.
有更好的方法吗?
推荐答案
此方案的设计取决于您要在15s内执行的操作.两种最合理的情况是每X进行15秒"或等待X发生或15秒钟,以较早者为准",这将导致代码截然不同.
The design of this depends on what you want doing for 15s. The two most plausible cases are "do this every X for 15s" or "wait for X to happen or 15s whichever comes sooner", which will lead to very different code.
这不会重复,但是如果您不希望执行15秒钟的操作,效率会更高(在执行任何操作时浪费的CPU更少).
This doesn't iterate, but if you want to do nothing for 15s is much more efficient (it wastes less CPU on doing nothing).
如果您真的想循环15秒,那么您的解决方案就可以了,只要您的代码不会花费太长时间即可.像这样:
If you really want to loop for 15s then your solution is fine, as long as your code doesn't take too long. Something like:
long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
// do something
// pause to avoid churning
Thread.sleep( xxx );
}
等待15秒或其他情况
如果您希望代码在15s后被中断,无论执行什么操作,都需要一个多线程解决方案.查看 java.util.concurrent 获取大量有用的对象.大多数锁定方法(如wait())都有一个超时参数. 信号量可能完全可以您需要什么.
Wait for 15s or some other condition
If you want your code to be interrupted after exactly 15s whatever it is doing you'll need a multi-threaded solution. Look at java.util.concurrent for lots of useful objects. Most methods which lock (like wait() ) have a timeout argument. A semaphore might do exactly what you need.
这篇关于在Java中运行代码x秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!