Update Date each second?
Hi fellow Java devvers :)
I've been trying to create a thread that would run the date object every 1 sec.. so far so good, It shows the time every 1 sec but i was wondering what is the better way of doing this? And also how do I print the date once and update the old one with the new date.
Thanks.
import java.text.SimpleDateFormat;
import java.util.Date;
publicclass MyTestextends Thread{
public MyTest (){}
publicvoid run(){
for(;;){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
Date currentDate =new Date();
SimpleDateFormat dateFormat =new SimpleDateFormat("h:mm:ss a");
String d = dateFormat.format(currentDate);
System.out.println(d);
}
}
publicstaticvoid main(String[] args){
MyTest m =new MyTest ();
m.run();
}
}
[1944 byte] By [
deAppela] at [2007-11-27 10:00:19]

1) You should not extend Thread you should implement Runnable. See the first entry in this FAQ for why http://forum.java.sun.com/ann.jspa?annID=9
2) That is not the proper way to start a Thread (whether created as Runnable or Thread). You must call the start method not the run method. You never call the run method directly. The VM does that for you.
3) I am not sure why you made a thread for this anyway. You aren't actually running in a seperate thread (see point 2) but when you do I don't know what the point is.
4) Rather than the sleep I would look at java.util.Timer and java.util.TimerTask
> 1) You should not extend Thread you should implement
> Runnable. See the first entry in this FAQ for why
> http://forum.java.sun.com/ann.jspa?annID=9
>
> 2) That is not the proper way to start a Thread
> (whether created as Runnable or Thread). You must
> call the start method not the run method. You never
> call the run method directly. The VM does that for
> you.
>
> 3) I am not sure why you made a thread for this
> anyway. You aren't actually running in a seperate
> thread (see point 2) but when you do I don't know
> what the point is.
>
> 4) Rather than the sleep I would look at
> java.util.Timer and java.util.TimerTask
Ya i thought so about point 1, I've created the new thread and called the start() method instead of the run()
4, got it
thanks!