我想在Java中编写一个循环,第一次启动就像这样:
I want to write a loop in Java that firs starts up and goes like this:
while (!x){ //wait one minute or two //execute code }我想这样做,以免它耗尽系统资源。在代码中实际发生的是它进入一个网站并检查是否已完成某些事情,如果没有完成,它应该等待一分钟直到它再次检查,并且当它完成时它只是继续。他们无论如何要在java中这样做吗?
I want to do this so that it does not use up system resources. What is actually going on in the code is that it goes to a website and checks to see if something is done, if it is not done, it should wait another minute until it checks again, and when its done it just moves on. Is their anyway to do this in java?
推荐答案使用 Thread.sleep(long millis) 。
导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于精度和准确度系统计时器和调度程序。该线程不会失去任何监视器的所有权。
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
一分钟(60 * 1000)= 60000 毫秒。
例如,此循环将每5秒打印一次当前时间:
For example, this loop will print the current time once every 5 seconds:
try { while (true) { System.out.println(new Date()); Thread.sleep(5 * 1000); } } catch (InterruptedException e) { e.printStackTrace(); }如果你的睡眠时间对于 int来说太大了/ code>,显式计算 long (例如 1000L )。
If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).
更多推荐
每分钟Java循环
发布评论