Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Running a thread twice [closed]

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?

like image 521
Airflow46 Avatar asked Nov 10 '13 11:11

Airflow46


2 Answers

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 Threads that take tasks as they come. This removes the overhead of spawning new Threads because it caches them.

like image 72
Boris the Spider Avatar answered Sep 29 '22 20:09

Boris the Spider


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

like image 22
Stephen C Avatar answered Sep 29 '22 21:09

Stephen C