Answer the question
In order to leave comments, you need to log in
How to get data from threads back to main in java?
The main method has
public static ArrayList<DataForDepth> list = new ArrayList<DataForDepth>(100);
for (int i = 0; i < 100; i++) {
MyRunnable mRnbl = new MyRunnable(i, list.get(i));
new Thread(mRnbl).start();
}
Answer the question
In order to leave comments, you need to log in
You can use Future. Or sync.
By the way, for multithreading, you need to use containers that are specially sharpened ... . And judging by the above code, you need to read the literature on multithreading in java, and not ask such things here. Then such questions will not arise.
There is a queue for this LinkedBlockingQueue
.
Threads write return values to it, labeled with the job id.
main reads from it and reconstructs the array of return values by their id, without relying on the order of the elements in the queue, which is not guaranteed.
Use collections as suggested above, such as queues or Maps. It is better to use from the java.util.concurrent package
. You can also use the new Callable interface -
docs.oracle.com/javase/7/docs/api/java/util/concur...
Which can just return a value, unlike Runnable.
Starting 100 threads is not a good idea. Unless, of course, you have a 100-core server or cluster.
Create an ExecutorPool with n + 1 threads. And shove your Callable in there. And then wait for the result on get()
Here is the official Oracle tutorial on how to do it. I'm sure it will help you figure it out.
https://blogs.oracle.com/CoreJavaTechTips/entry/ge...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question