periodically doing a task inside run method of a thread

W

wanwan

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.
 
O

Oliver Wong

wanwan said:
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
 
J

James McGill

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top