有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么单线程执行器服务使用4核?

我有以下使用单线程执行器服务的代码,但运行它时使用了我机器上的所有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
    }
}

这与mine的另一个问题有关


共 (1) 个答案

  1. # 1 楼答案

    刚刚在我的机器上试用,我的CPU使用率达到35%(4核)。请注意,程序中至少有2个线程(主线程和执行线程)

    但是,如果我将N增加到100,CPU使用率将上升到90+%,因为很多时间都花在完整的GCs上(而我运行的是2GB的堆)

    因此,看起来您的单个线程太忙,任务开始累积,等待执行

    您可以尝试使用以下JVM参数运行代码:-XX:+PrintGC

    我的机器上的输出如下所示:

    [GC 511999K->465632K(1962688K), 1.0286778 secs]
    [GC 977632K->922984K(1962688K), 1.1999209 secs]
    [GC 1434984K->1407984K(1962688K), 1.2421900 secs]
    [Full GC 1407984K->1373358K(1962688K), 9.8320408 secs]
    [Full GC 1885358K->1822040K(1962688K), 7.5170472 secs]
    [Full GC 1877375K->1870974K(1962688K), 7.6635945 secs]
    [Full GC 1877374K->1876550K(1962688K), 7.6705722 secs]
    [Full GC 1877374K->1877272K(1962688K), 7.8381579 secs]
    [Full GC 1877372K->1877357K(1962688K), 8.6095022 secs]