I need to have a task repeated periodically in a thread . for now I'm
using inside the run method :
long pausetime = 2000;
long p = System.currentTimeMillis();
long q;
while(true){
if (p < (q = System.currentTimeMillis() - pausetime)) {
p = q + pausetime;
// modify this object's variables
}
}
// do something
I think this approach is bad because the looped if statement requires
too much work as I increase the number of threads.
I can't use sleep() of Timer object because I'm not calling from
outside the thread. Or if it's possible to use them inside the run
method, I don't know how to do it.
Please help.
wanwan - 24 Feb 2006 21:55 GMT
haha, i'm so sorry. I found my error
Oliver Wong - 24 Feb 2006 21:56 GMT
>I need to have a task repeated periodically in a thread .
[...]
> Please help.
See http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html
<quote>
A facility for threads to schedule tasks for future execution in a
background thread. Tasks may be scheduled for one-time execution, or for
repeated execution at regular intervals.
</quote>
You'll probably want to use this constructor:
<quote>
schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution,
beginning after the specified delay.
</quote>
Which means you'll probably want to read the JavaDocs for TimerTask:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/TimerTask.html
- Oliver
James McGill - 24 Feb 2006 21:58 GMT
> I think this approach is bad because the looped if statement requires
> too much work as I increase the number of threads.
Busy wait loop is never good if performance is an issue.
> I can't use sleep() of Timer object because I'm not calling from
> outside the thread. Or if it's possible to use them inside the run
> method, I don't know how to do it.
You should be able to use sleep() inside the run() method. See this
example from Sun that does exactly that:
http://java.sun.com/docs/books/tutorial/essential/threads/simple.html
And I'll take your word for it, but I'm sure I'd try to find a way to
make it a TimerTask and use java.util.Timer on it somehow.