作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!