-1

So I made a class that extends Thread class and I have a main class that calls start(). I have created 1000 threads to run my program in this way:

int ThreadNum = 1000;
for(int i=0; i<ThreadNum; i++){
   Thread_Class function = new Thread_Class();// The Thread_Class is the one that extends the Thread class.
function.start();                    }

does this make 1000 of threads? And how do I collect the data backs from all the threads?

Thank you so much!! I all appreciate!

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • yes you are creating `1000` threads and what data you want to collect back? – Ryuzaki L Sep 20 '19 at 03:04
  • I let each Thread run a function that will produce a number as a double type, and I want to collect them all from all these 1000 Threads and be able to use the collected data and do something else. – user9894502 Sep 20 '19 at 03:10

1 Answers1

2

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

You have created Threads 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.

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35
  • 1
    There's no such thing that states `future.get` should always be called with timeouts. If there's any please show it in the documentation. – Ravindra Ranwala Sep 20 '19 at 14:30