gpt4 book ai didi

java - 在Java中,如何将对象从工作线程传递回主线程?

转载 作者:行者123 更新时间:2023-12-02 08:03:31 26 4
gpt4 key购买 nike

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

如何将结果传回mainresults[i]

如何将this传递给WorkerThread

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

这样就可以了

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

最佳答案

为什么不使用 Callables和一个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 - 在Java中,如何将对象从工作线程传递回主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com