How to start and manage Java threads?
The 开发者_StackOverflowfollowing 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();
}
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.
Agree that ExecutorService is the way to go. I have a utility class that uses ExecutorService to run a arbitrary number of tasks, collect the results and return them as a list. ExecutorService will do all of the housekeeping for you.
精彩评论