Re: Java Timer



"sconeek" <sconeek@xxxxxxxxx> wrote in message
news:1133324375.510734.223260@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
>I wouldnt mind using that either. i just need to know how to implement
> it.


LOL

Here is an example :)

import java.lang.Thread;

public class BeerSong implements Runnable {
Thread runner;
BeerSong(){
if (runner == null) { //start the song
runner = new Thread(this);
runner.start();
}
}
public void run() {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0 && runner != null){
WaitAMoment();
if (beerNum == 1)
word = "bottle";
System.out.println(beerNum + " " + word + " of beer on the wall");
System.out.println(beerNum + " " + word + " of beer.");
System.out.println("Take one down");
System.out.println("Pass it around.");
beerNum = beerNum - 1;
if (beerNum > 0)
System.out.println(beerNum + " " + word + " of beer on the wall");
else
System.out.println("No more bottles of beer on the wall");
}

}
protected void WaitAMoment() {
try {
Thread.sleep(300);
} catch (InterruptedException e) { };
}
public static void main (String[] args) {
new BeerSong();
}
}


I like to put my sleep into it's own function :)

Of course, you don't need to make a special thread to wait.

You could just insert this code

try {
java.lang.Thread.currentThread().sleep(10000);
} catch (Exception e) {
// e.printStackTrace();
}

Just replace the 10000 with the number of milliseconds you want to wait :)

This is much more efficient than a loop.

--
LTP

:)


.


Quantcast