2012-11-30 30 views
2

我有下面的代碼,它使用單線程執行程序服務,但運行它使用我的機器上的所有4個核心(每個核心的平均使用率約爲80%)。爲什麼SingleThreaded Executor服務使用4個內核?

問題是爲什麼會發生這種情況? 我真的沒有興趣在這裏找斐波那契!

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

你能發佈簡短而*完整*程序,演示了此問題?我們需要看到FibSampler。 –

+0

它在代碼中。向下滾動! :) – Mahdi

+0

就核心利用率而言,它並不意味着您的代碼正在利用所有核心。操作系統也可以利用這些內核。所以你的問題是無效的。就你的其他問題而言,僅僅使用線程不會提供性能,你必須對它進行優化,以便在並行環境中得到最佳使用。算法也應該是可以並行執行的。 –

回答

4

剛剛在我的機器上試過,我的總CPU使用率達到了35%(4核)。請注意,程序中至少有2個線程(主線程和執行程序線程)。

但是,如果我將N增加到100,則CPU使用率會上升到90 +%,因爲在完整GC中花費了大量時間(並且我正在運行2GB堆)。

所以看起來你的單線程太忙了,任務開始積累,等待被執行。

你可以嘗試運行具有以下JVM參數代碼:-XX:+PrintGC

我的機器上輸出的樣子:

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

相關問題