在Java中,如何将对象从辅助线程传递回主线程? [英] In Java, how to pass the objects back to Main thread from worker threads?

查看:77
本文介绍了在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]);

推荐答案

为什么不使用

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

这篇关于在Java中,如何将对象从辅助线程传递回主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆