Skip to content
Advertisement

In Java, how to pass the objects back to Main thread from worker threads?

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

How to pass the result back to main‘s results[i] ?

How about passing this to WorkerThread,

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

so that it could

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

Advertisement

Answer

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
  }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement