Rob makes a good point. using a timer is generally preferred. the class i posted runs in its own thread so it can be an exception. even so, if i wrote it today instead of 8 years ago i would use a Timer instead of Thread.sleep().
Joined: Jun 05, 2010
Frankly speaking, i didn't understood Randall's code. May be, it looks very difficult. Or, may be, i am running from difficult codes.
Can you(or anyone) provide me a link , or package details, or any thing which would be of great help?
sorry if it seems i am hijacking this thread but this is on topic anyway. i got to thinking about changing my old code to use a Timer and realized there is a fundamental difference. in the original app i created 8 Horse objects, each running in it's own thread, and they all wanted to run the synchronized method parent.postResults(name);
if i remember correctly, when the lock on the synchronized code becomes available, a waiting thread at random gets chosen. i think that using a Timer they will be "competing" for the EDT instead. i also think the EDT queues the waiting events(so it is not random).
this brings up a question. would i still need to synchronize the postResults() method? or will the EDT take care of that?
i refactored the program to use a Timer, but this is the rare case where using Thread.sleep() works better. i have 8 Horse threads that all call the synchronized method postResults(). that method lists the names of all the Horses and how they finished in the race. with the original code postResults() completed almost instantly. using a Timer it takes a second or so. not all that surprising if you think about it. here is the code anyway, for those who want to see a Timer version.
Randall's way is correct, except for you're usually supposed to use a timer. See this on timers: http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html A timer triggers an event every <delay> milliseconds. So if you have a timer that triggers an event, inside the corresponding actionPerformed() method you should put code to increase the coordinates of the Horse.