我有以下代码使用单线程执行器服务,但运行它使用我机器上的所有 4 个内核(每个内核平均使用率约为 80%)。
问题是为什么会这样?而且我真的对找到斐波那契不感兴趣!
public class MainSimpler {
static int N=35;
static AtomicInteger result = new AtomicInteger(0), pendingTasks = new AtomicInteger(1);
static ExecutorService executor;
public static void main(String[] args) {
executor = Executors.newSingleThreadExecutor();
long before = System.currentTimeMillis();
System.out.println("Fibonacci "+N+" is ... ");
executor.submit(new FibSimpler(N));
waitToFinish();
System.out.println(result.get());
long after = System.currentTimeMillis();
System.out.println("Duration: " + (after - before) + " milliseconds\n");
}
private static void waitToFinish() {
while (0 < pendingTasks.get()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
class FibSimpler implements Runnable {
int N;
FibSimpler (int n) { N=n; }
@Override
public void run() {
compute();
MainSimpler.pendingTasks.decrementAndGet();
}
void compute() {
int n = N;
if (n <= 1) {
MainSimpler.result.addAndGet(n);
return;
}
MainSimpler.executor.submit(new FibSimpler(n-1));
MainSimpler.pendingTasks.incrementAndGet();
N = n-2;
compute(); // similar to the F/J counterpart
}
}
这与我的另一个问题有关。