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");
}
this method sucks
ReplyDeleteit 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
good idea. thanks for that.
ReplyDeleteLink to Thread.sleep
caboom: Thanks! You just saved me hours of hair pulling!
ReplyDelete"Thread.sleep(1000); (for one second)
ReplyDeleteand 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?
Mike, this is how you would do it.
ReplyDeletepublic 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");
}
}
Threading is not so good either, there are better ways to do that by creating a timer and then a action listener.
ReplyDeleteTROLOLOL
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete