【发布时间】:2016-11-09 12:47:54
【问题描述】:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Fibonacci {
private static long[] value;
public static void main(String args[]) throws InterruptedException {
int n;
try {
n = Integer.parseInt(args[0]);
} catch (Exception e) {
throw new RuntimeException(" number n");
}
value = new long[n + 1];
long start = System.nanoTime();
System.out.print("Dynamic Programming = " + fibon(n));
long end = System.nanoTime();
System.out.println("\t time = " + (end - start) + "ns");
start = System.nanoTime();
System.out.print("Sequence = " + Sequence(n));
end = System.nanoTime();
System.out.println("\t time = " + (end - start) + "ns");
start = System.nanoTime();
//int nThreads = Runtime.getRuntime().availableProcessors();
int nThreads = 30;
ExecutorService executorService = Executors
.newFixedThreadPool(nThreads);
int result;
try {
result = fibonacciSum(n, executorService); }
catch (ExecutionException e) {
throw new RuntimeException("Thread Interuppted "); }
System.out.print(" MultiThreading = " + result);
end = System.nanoTime();
System.out.println("\t time = " + (end - start) + "ns");
}
public static long fibon(int n) {
value[0] = 1;
value[1] = 1;
if (n <= 2)
return 1;
else if (value[n - 1] != 0)
return value[n];
for (int j = 2; j <= n; j++) {
value[j] = fibon(j - 2) + fibon(j - 1); }
return value[n];
}
public static long Sequence(int n) {
if (n <= 2)
return 1;
else
return (Sequence(n - 1) + Sequence(n - 2));
}
private static class FibonacciThread implements Runnable {
int index;
int result;
ExecutorService executorService;
public FibonacciThread(int index) {
this.index = index;
}
public void run() {
try {
this.result = fibonacciSum(index, executorService);
} catch (Exception e) {
throw new RuntimeException("Thread interupted");
}
}
}
private static int fibonacciSum(int index, ExecutorService executorService)
throws InterruptedException, ExecutionException {
if (index == 1 || index == 2) {
return 1;
} else {
FibonacciThread fibonacciThread1 = new FibonacciThread(index - 2);
fibonacciThread1.executorService=executorService;
Future future = executorService.submit(fibonacciThread1);
Object object = future.get();
int resultPart2 = fibonacciSum(index - 1, executorService);
int result = fibonacciThread1.result + resultPart2;
//executorService.shutdown();
return result;
}
}
}
运行上述代码后出现此错误。
线程“main”中的异常 java.lang.RuntimeException: Number n at Fibonacci.main(Fibonacci.java:16)
请告诉我如何解决这个问题。 该程序假定工作如下:在命令行中,用户将输入程序要生成的斐波那契数。然后程序将创建一个单独的线程来生成斐波那契数,将序列放入线程可以共享的数据中(数组可能是最方便的数据结构)。
【问题讨论】:
-
确保你用
java Fibonacci <value-of-n>启动你的程序,否则你会得到这个异常,因为你的程序除了一个参数 -
你如何运行你的程序?顺便说一句,你觉得
throw new RuntimeException(" number n");做什么? -
请将您的示例代码缩减为minimal reproducible example。最少的代码通常不应该包含计时例程,除非问题是专门针对那个方面的。
标签: java multithreading fibonacci