如何将参数传递给线程并获取返回值? [英] How to pass a parameter to a thread and get a return value?
本文介绍了如何将参数传递给线程并获取返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
类调用此方法).
Of course, thread.getResult()
doesn't work (it tries to invoke this method from the Thread
class).
您得到我想要的.如何在Java中实现这一目标?
You get what I want. How can I achieve this in Java?
推荐答案
这是线程池的一项工作.您需要创建一个Callable<R>
,该Callable<R>
返回一个值并将其发送到线程池.
This a job for thread pools. You need to create a Callable<R>
which is Runnable
returning a value and send it to a thread pool.
此操作的结果是Future<R>
,它是指向此作业的指针,该指针将包含计算值,或者如果作业失败则不包含该值.
The result of this operation is a Future<R>
which is a pointer to this job which will contain a value of the computation, or will not if the job fails.
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
这篇关于如何将参数传递给线程并获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文