In Java, how to pass the objects back to Main thread from worker threads? Take the following codes as an example:
JavaScript
x
main(String[] args) {
String[] inputs;
Result[] results;
Thread[] workers = new WorkerThread[numThreads];
for (int i = 0; i < numThreads; i++) {
workers[i] = new WorkerThread(i, inputs[i], results[i]);
workers[i].start();
}
.
}
.
class WorkerThread extends Thread {
String input;
int name;
Result result;
WorkerThread(int name, String input, Result result) {
super(name+"");
this.name = name;
this.input = input;
this.result = result;
}
public void run() {
result = Processor.process(input);
}
}
How to pass the result
back to main
‘s results[i]
?
How about passing this
to WorkerThread
,
JavaScript
workers[i] = new WorkerThread(i, inputs[i], results[i], this);
so that it could
JavaScript
mainThread.reults[i] = Processor.process(inputs[i]);
Advertisement
Answer
Why don’t you use Callable
s and an ExecutorService
?
JavaScript
main(String[] args) {
String[] inputs;
Future<Result>[] results;
for (int i = 0; i < inputs.length; i++) {
results[i] = executor.submit(new Worker(inputs[i]);
}
for (int i = 0; i < inputs.length; i++) {
Result r = results[i].get();
// do something with the result
}
}