Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and manage Java threads?

The following code works, fine, but i wonder .. conceptually, is it correct? Start the threads, wait for them to join. Should ThreadPool be used instead?

If possible, please comment

List<Thread> threads = new ArrayList<Thread>();

for (Test test : testsToBeExecuted) {
  Thread t = new Thread(test);
  threads.add(t);
  t.start();
}

for (Thread thread : threads) {
  thread.join();
}
like image 361
James Raitsev Avatar asked Jun 20 '11 18:06

James Raitsev


1 Answers

Conceptually it looks fine. You can use an ExecutorService which you create one like:

ExecutorService service = Executors.newFixedThreadPool(testsToBeExecuted.size());

Thenyou would create a list of Callables and invokeAll on the executor service itself. That in essence will do the same thing.

like image 131
John Vint Avatar answered Sep 20 '22 13:09

John Vint