I want to start several callable threads in the same time(in loop), and want to return some information from everyone in main thread. How to realise this?
4 Answers
It's impossible to say the best approach from your question, because we know nothing about the use case! But generally speaking you could create a thread pool using Executors.newFixedThreadPool()
, then submit generic Callable<T>
objects to the thread pool - you'll get back a Future<T>
.
In the main thread, you can then loop over the futures, calling each one of the get()
methods which will block until the corresponding callable has finished execution in the thread pool.

- 70,193
- 21
- 157
- 216
When creating the threads in the main thread, you could keep a reference to them and get data through these references. The pseudo-code would look like this:
int nSize = <some nomber>;
MyThread myThreadArray[] = new MyThread[nSize];
for(int i = 0; i < nSize; i++) {
myThreadArray[i] = new MyThread();
// Init and start the thread.
}
// Wait for all thread to end.
for(int i = 0; i < nSize; i++) {
myThreadArray[i].getData();
}
Any type of List
could be used instead of a fixed size array.
Edit/Addition:
Instead of keeping the data in the child threads, you could also allocate it in the main thread and give a reference to it when creating the child thread:
int nSize = <some nomber>;
MyThreadData myThreadDataArray[] = new MyThreadData[nSize];
for(int i = 0; i < nSize; i++) {
Thread thread = new MyThread(myThreadDataArray[i]);
// Init and start the thread.
}
// Wait for all thread to end.
for(int i = 0; i < nSize; i++) {
// Do something with myThreadDataArray[i].
}
This would allow the gc to reclaim the Thread
objects sooner if you need to work with the thread data for a long time after the thread termination.

- 16,077
- 4
- 26
- 34
from my understanding, the precedence of start and stop of threads in Java is not guaranteed. Some threads may go to wait mode after they are started to give way to another thread, perhaps because it is awaiting for I/O.
Here are some questions i have asked which may have what you want - starting threads at the same time using loops.
Why is it that threads 10000 start() calls take more time than 10000 run() calls?

- 1
- 1

- 23,028
- 51
- 143
- 215
I don't know what is are your requirements.But i can give you little path. You can generate unique id for each thread and put that id with null value field in (database)somewhere.And make generated thread to update the table that they are belongs to(id).After that you can check the value is updated or not and get values.

- 4,044
- 5
- 25
- 37