Yoav Levavi
Yoav Levavi

Reputation: 85

How to use timer in java without using thread?

How can I make a java program wait X seconds without usingThread.sleep?

public class newClass{
     public static void main(String[] args){
           for(int i = 0; i < 10; i++){
               //Wait X second 
               System.out.println("Hello");
           }
     }
}

Thanks for any help!!

I need the program won't freeze while it's counting

Upvotes: 3

Views: 5067

Answers (5)

dlschon
dlschon

Reputation: 66

You can use Java's Timer and TimerTask class for this.

 import java.util.Timer;
 import java.util.TimerTask;
 public class newClass extends TimerTask{
      int i = 10;
      static Timer timer;

      @Override
      public void run(){
           System.out.println("hello");
           i--;
           if (i == 0)
               timer.cancel();

      }

      public static void main(String[] args){
           TimerTask timerTask = new newClass();
           timer = new Timer(false);
           timer.scheduleAtFixedRate(timerTask, 0, 5 * 1000);
      }
 }

And Timer works on its own thread in the background so it won't freeze up the rest of your program!

Upvotes: 1

Adam Martinu
Adam Martinu

Reputation: 253

Seems like you want your program to start, and after X time has elapsed print "Hello" on the output stream?

  1. Do as ocozalp suggested
  2. Or use the Thread.sleep(x); method

Both options will give you exactly the same result, although option 2 is preferred, since you allow the CPU to do something else while your main thread is sleeping, and because using option 1 makes your intention with the program less clear.

Upvotes: 0

SteveS
SteveS

Reputation: 1030

What you are really looking for is a multi-thread implementation. That is what will allow you to continue interacting with one area of the application while waiting for another to finish processing.

Edit Ok, after further clarification in the comments, sounds like this is not what you are looking for. Perhaps you can register each child in a HashMap with the time that they started. Then monitor the map to see when time is up.

Upvotes: 0

ian
ian

Reputation: 705

If your issue is that you do not want your program to freeze, consider using threads. This example might be similar to what you want to achieve: http://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html.

Upvotes: 1

ocozalp
ocozalp

Reputation: 78

It is a bad approach but you can use this:

 public class newClass{
      public static void main(String[] args){
           int X = 5;
           for(int i = 0; i < 10; i++){
               long s = System.nanoTime();
               while( (System.nanoTime() - s) / 1000000000 < X);
               System.out.println("Hello");
           }
      }
 }

You can also use

System.currentTimeMillis()

Upvotes: 0

Related Questions