在Java中,如何将对象从工作线程传回主线程?以以下代码为例:
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);
}
}
怎么传result
回给main
的results[i]
?
this
传递给WorkerThread
,怎么样
workers[i] = new WorkerThread(i, inputs[i], results[i], this);
这样它就可以
mainThread.reults[i] = Processor.process(inputs[i]);