From another post:
If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.
How is this done?
I would use another layer of abstraction. Use an ExecutorService
.
Here is a simple example:
public static void main(String args[]) throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
final class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Running my task.");
}
};
for (int i = 0; i < 10; ++i) {
service.submit(new MyTask());
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
}
Just dump your task into the service
as many times as you want.
The ExecutorService
is a thread pool - it has a number of Thread
s that take tasks as they come. This removes the overhead of spawning new Thread
s because it caches them.
Basically, a thread cannot be restarted.
So if you want a reusable "thread", you are really talking about a Runnable
. You might do something like this:
Runnable myTask = new Runnable() {
public void run() {
// Do some task
}
}
Thread t1 = new Thread(myTask);
t1.start();
t1.join();
Thread t2 = new Thread(myTask);
t2.start();
(This is purely for illustration purposes only! It is much better to run your "runnables" using a more sophisticated mechanism, such as provided by one of the ExecutorService
classes, which is going to manage the actual threads in a way that avoids them terminating.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With