在 Java 中运行代码 x 秒? [英] Run code for x seconds in Java?

查看:25
本文介绍了在 Java 中运行代码 x 秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个迭代 15 秒的 java while 循环.我认为这样做的一种方法是存储当前系统时间 + 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.

有更好的方法吗?

推荐答案

这个的设计取决于你想在 15 秒内做什么.两个最合理的情况是每 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.

Thread.sleep(15000)

这不会迭代,但如果你想在 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 秒或其他一些条件

如果您希望代码在 15 秒后被中断,无论它在做什么,您都需要一个多线程解决方案.看看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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆