在Java中,如何將對象從工作線程傳遞迴主線程?以下面的代碼爲例:在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]);
你真的應該只使用'Executors.newFixedThreadPool(numThreads).invokeAll(...)' – oldrinb
@veer爲什麼?我最多隻能運行10個線程。 – JackWM