nmelssx
nmelssx

Reputation: 100

Print out a statement after 2 seconds

I'm trying to make it print out how long time has passed in seconds after 2 seconds. I don't know what I'm doing wrong. Please help.

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

Upvotes: 1

Views: 343

Answers (2)

user2864740
user2864740

Reputation: 61875

The "X" problem is the logic in the posted code is wrong - it doesn't consider when the operation was started, so it'll never know how long was waited. Consider the following code which, while not ideal here, is a common idiom when dealing with times and loops waiting for such to occur.

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!");

Upvotes: 0

Anubian Noob
Anubian Noob

Reputation: 13596

You can use the Thread.sleep() method to wait a number of milliseconds:

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

Upvotes: 6

Related Questions