What is the best way to restart a thread?

G

Gordon Beaton

How does a guy go about restarting a finished thread? I have a class
that extends thread and I want to be able to restart it once it has
finished his task. Is there anyway I can get the thread to restart
itself by say having a method which I can call. Thanks

No, you need to start a new thread. This has always been the case and
it is often repeated here, however AFAICT it wasn't until 1.5 that the
javadocs actually said so.

An alternative is to not let the thread terminate at all (i.e. don't
ever return from run()). When it's finished its task, block it in a
call to wait() until you call a custom method to reinitialize any data
and let it continue with a new task.

Note that for most uses it's considered better style to implement
Runnable than extend Thread.

/gordon
 
K

Ken Adams

How does a guy go about restarting a finished thread? I have a class that
extends thread and I want to be able to restart it once it has finished his
task. Is there anyway I can get the thread to restart itself by say having a
method which I can call. Thanks
 
S

Steve Horsley

Ken said:
How does a guy go about restarting a finished thread? I have a class that
extends thread and I want to be able to restart it once it has finished his
task. Is there anyway I can get the thread to restart itself by say having a
method which I can call. Thanks

As Gordon says, you cannot restart a dead Thread.

I always advise that you use Runnables instead of extending Thread, to reduce
the confusion that arises when one Thread's thread calls another Thread's
methods. Another benefit in this case is that you can always start another
Thread on an existing Runnable, which probably achieves the restart that you
are looking for.

Of course, you can always start a new Thread on an existing Thread, because
a Thread is Runnable. But perverts like that don't get let out very often,
fortunately.

Steve
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top