在Java中,如何将对象从辅助线程传递回主线程?

问题描述:

在Java中,如何将对象从辅助线程传递回主线程?以以下代码为例:

In Java, how to pass the objects back to Main thread from worker threads? Take the following codes as an example:

  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传递回mainresults[i]吗?

如何将this传递给WorkerThread

workers[i] = new WorkerThread(i, inputs[i], results[i], this);

以便可以

mainThread.reults[i] = Processor.process(inputs[i]);

为什么不使用 ExecutorService ?

Why don't you use Callables and an ExecutorService?

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
  }
}