Friday, September 08, 2006

Java. Pause Method

A nice little method to create a 'pause' effect in Java.


public static void doPause(int iTimeInSeconds){
long t0, t1;
System.out.println("timer start");
t0=System.currentTimeMillis( );
t1=System.currentTimeMillis( )+(iTimeInSeconds*1000);

System.out.println("T0: "+t0);
System.out.println("T1: "+t1);

do {
t0=System.currentTimeMillis( );

} while (t0 < t1);

System.out.println("timer end");

}



8 comments:

  1. this method sucks
    it uses loops and consumes all of the cpu for as long the loop lasts.

    use:

    Thread.sleep(1000); (for one second)
    and catch the InterruptedException

    ReplyDelete
  2. caboom: Thanks! You just saved me hours of hair pulling!

    ReplyDelete
  3. "Thread.sleep(1000); (for one second)
    and catch the InterruptedException"

    I'm a little new to progamming - could you post an example of this and maybe explain it a little. For example, what does "catch" and "InterruptedException" mean and should they be a part of the program - if so - how?

    ReplyDelete
  4. Mike, this is how you would do it.

    public class Wait {
    public static void oneSec() {
    try {
    Thread.currentThread().sleep(1000);
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    public static void manySec(long s) {
    try {
    Thread.currentThread().sleep(s * 1000);
    }
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    This is how to test it.

    public class TestWait {
    public static void main(String args[]) {
    System.out.println("Wait one second");
    Wait.oneSec();
    System.out.println("Done\nWait five seconds");
    Wait.manySec(5);
    System.out.println("Done");
    }
    }

    ReplyDelete
  5. Threading is not so good either, there are better ways to do that by creating a timer and then a action listener.

    ReplyDelete
  6. Anonymous6:47 AM

    TROLOLOL

    ReplyDelete
  7. Anonymous7:21 AM

    This comment has been removed by a blog administrator.

    ReplyDelete