gpt4 book ai didi

java - 如何向线程传递参数并获取返回值?

转载 作者:行者123 更新时间:2023-12-02 03:30:05 29 4
gpt4 key购买 nike

public class CalculationThread implements Runnable {

int input;
int output;

public CalculationThread(int input)
{
this.input = input;
}

public void run() {
output = input + 1;
}

public int getResult() {
return output;
}
}

其他地方:

Thread thread = new Thread(new CalculationThread(1));
thread.start();
int result = thread.getResult();

当然,thread.getResult() 不起作用(它尝试从 Thread 类调用此方法)。

你得到了我想要的。我怎样才能在Java中实现这一点?

最佳答案

这是线程池的工作。您需要创建一个 Callable<R>这是 Runnable返回一个值并将其发送到线程池。

此操作的结果是 Future<R>这是指向此作业的指针,它将包含计算值,或者如果作业失败则不会包含计算值。

public static class CalculationJob implements Callable<Integer> {
int input;

public CalculationJob(int input) {
this.input = input;
}

@Override
public Integer call() throws Exception {
return input + 1;
}
}

public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(4);

Future<Integer> result = executorService.submit(new CalculationJob(3));

try {
Integer integer = result.get(10, TimeUnit.MILLISECONDS);
System.out.println("result: " + integer);
} catch (Exception e) {
// interrupts if there is any possible error
result.cancel(true);
}

executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);
}

打印:

result: 4

关于java - 如何向线程传递参数并获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221408/

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