import java.math.BigInteger;
import java.util.concurrent.*;
public class MultiThreadedFib {
private ExecutorService executorService;
public MultiThreadedFib(final int numberOfThreads) {
executorService = Executors.newFixedThreadPool(numberOfThreads);
}
public BigInteger getFibNumberAtIndex(final int index)
throws InterruptedException, ExecutionException {
Future<BigInteger> indexMinusOne = executorService.submit(
new Callable<BigInteger>() {
public BigInteger call()
throws InterruptedException, ExecutionException {
return getNumber(index - 1);
}
});
Future<BigInteger> indexMinusTwo = executorService.submit(
new Callable<BigInteger>() {
public BigInteger call()
throws InterruptedException, ExecutionException {
return getNumber(index - 2);
}
});
return indexMinusOne.get().add(indexMinusTwo.get());
}
public BigInteger getNumber(final int index)
throws InterruptedException, ExecutionException {
if (index == 0 || index == 1)
return BigInteger.valueOf(index);
return getFibNumberAtIndex(index - 1).add(getFibNumberAtIndex(index - 2));
}
}
im gonig用java线程计算斐波那契数列以减少计算时间但答案错误虽然它似乎是真的。 另一个问题是在编号为35的新线程顶端出现内存不足异常。 请帮帮我 很多问候...用java中的线程计算斐波那契线程
是什么让你觉得使用线程在这里会有所帮助?有一种天然的O(n)解决方案是不可并行的......这是一种比所有这些复杂性更好的方法,IMO。 –
你是否意识到每次递归都会使得任务数量增加一倍?为你自己判断你的计算机系统将承担多长时间,假设一个任务需要* some *内存(例如,我们可以假设一个任务只需要4个字节,需要多少次递归来填充你的内存?) – Ingo