2秒后打印一份声明

时间:2014-08-31 02:33:20

标签: java

我正在努力打印出2秒钟后经过多长时间的时间。我不知道我做错了什么。请帮忙。

while(System.nanoTime()/1000000000<2){
System.out.println(System.nanoTime()/1000000000);
}

2 个答案:

答案 0 :(得分:6)

您可以使用Thread.sleep()方法等待几毫秒:

Thread.sleep(2000);
System.out.println("Two seconds have passed");

答案 1 :(得分:0)

&#34; X&#34;问题是发布的代码中的逻辑是错误的 - 它没有考虑操作何时开始,因此它永远不会知道等待了多长时间。考虑以下代码,虽然在这里不理想,但在处理等待发生这种情况的时间和循环时,它是一个 common 习语。

long start = System.nanoTime();
while (true) {
   long now = System.nanoTime();
   long elapsed = now - start;
   if (elapsed >= (2 * 1000000000)) {
      // Yup, more than 2s between when we started and now.
      break;
   }
   // Otherwise, make toast (ie. make the CPU get hot)..
   // ..but we can help that a bit with a "yield" - run it with and without
   // the following line commented and view the CPU usage in a process monitor.
   Thread.sleep(0);
}
System.out.println("Time up!");
相关问题