H
H
hudrogen2015-12-04 15:47:39
Java
hudrogen, 2015-12-04 15:47:39

How to get data from threads back to main in java?

The main method has

public static ArrayList<DataForDepth> list = new ArrayList<DataForDepth>(100);

Let's assume that the sheet is filled with data
. Next, I run threads in a loop, each thread processes an element of the sheet (mathematical operations).
for (int i = 0; i < 100; i++) {
      MyRunnable mRnbl = new MyRunnable(i, list.get(i));
      new Thread(mRnbl).start();	
    }

How can I collect the results of stream processing in maine into another ArrayList res?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
Y
YV, 2015-12-06
@targetjump

See ForkJoinPool

B
bromzh, 2015-12-04
@bromzh

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.

N
nirvimel, 2015-12-04
@nirvimel

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.

P
protven, 2015-12-04
@protven

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.

V
volyihin, 2015-12-06
@volyihin

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 question

Ask a Question

731 491 924 answers to any question