The way of constructing Threads in your question is just fine, but you are spinning a new Thread
for every iteration in the loop which is a very bad idea.
Constructing a new Thread is a costly affair you must refrain from. To alleviate this problem, ThreadPool
is made which contains Thread
s.
You have created Thread
s successfully, but it wont return a value. Note that start method is responsible for only starting the thread. You can either wait/interrupt the spawned thread while it is working. There is no way for returning an Object.
From the docs of Runnable
,
A Runnable, however, does not return a result and cannot throw a
checked exception.
And yeah, class Thread implements Runnable
. You have created objects of classes extending Thread
. So the behaviour is same for you.
Alternate would be to go ahead with Callable
as answered by @Ravindra.
From the docs of Callable
A task that returns a result and may throw an exception.
which is exactly what you need.
PS: Also, note that future.get()
is a blocking call. And is always recommended to use it with timeouts.