How to start and manage Java threads?

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

If possible, 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(); } 
+6
source share
2 answers

Conceptually, it looks good. You can use the ExecutorService that you create, for example:

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

Then you will create a list of Callables and invokeAll in the executing service itself. This essentially will do the same.

+9
source

Agree that ExecutorService is the way to go. I have a utility class that uses an ExecutorService to run an arbitrary number of tasks, collects the results, and returns them in a list. ExecutorService will do all the homework for you.

0
source

Source: https://habr.com/ru/post/890948/


All Articles