callable方法返回BigInteger类型数值
时间: 2023-12-22 15:06:27 浏览: 22
在Java中,BigInteger类提供了一个称为“callable”的方法,该方法返回一个BigInteger类型的数值。callable方法返回一个Callable类型的对象,该对象可以用于在另一个线程中计算BigInteger值。以下是一个示例:
```
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class BigIntegerCallableExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<BigInteger> callable = new Callable<BigInteger>() {
@Override
public BigInteger call() throws Exception {
BigInteger result = BigInteger.valueOf(1);
for (int i = 2; i <= 100; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
};
FutureTask<BigInteger> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("Waiting for calculation result...");
BigInteger result = futureTask.get();
System.out.println("Result: " + result);
}
}
```
在上面的示例中,我们创建了一个Callable对象,该对象计算从1到100的阶乘,并返回结果。我们使用FutureTask将Callable对象封装成一个可运行的任务,并将其提交到一个新线程中。然后我们等待计算结果,并在控制台打印输出。注意,由于计算可能需要一些时间,我们使用了get()方法阻塞当前线程,直到计算完成并返回结果。