2014-10-11 28 views
1

我想了解線程創建和同步所需的時間。我知道我應該使用ThreadMXBean,但我找不到使用ThreadMXBean和Callable接口來演示此示例的簡單示例。線程創建和同步所需的時間

package teststckofw; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 

public class TestStckOfw { 

    public static void main(String[] args) throws ExecutionException { 
     int i = 0; 
     int processed = 0; 
     while (i < 10) { 
      Parallel parallel1 = new Parallel(); 
      Parallel parallel2 = new Parallel(); 

      ExecutorService exec1 = Executors.newCachedThreadPool(); 
      List<Callable<Integer>> tasks1 = new ArrayList<>(); 
      try { 
       tasks1.add(parallel1); 
       tasks1.add(parallel2); 
       try { 
        List<Future<Integer>> futures = exec1.invokeAll(tasks1); 
        int flag = 0; 
        for (Future<Integer> f : futures) { 
         Integer res = f.get(); 
         if (res != 0) { 
          processed = res; 
         } 
         if (!f.isDone()) { 
          flag = 1; 
         } 
        } 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } finally { 
       exec1.shutdown(); 
      } 
      i++; 
     } 
    } 
    /**************************************/ 
    static class Parallel implements Callable<Integer> { 
     @Override 
     public Integer call() throws Exception {    
      int a = 2 + 2; // do something... 
      return a; 
     } 
    } 
} 

編輯: 我與許多迭代(遠遠超過10)的很長一段時間循環中需要的所有線程的信息。我可以通過使用線程轉儲獲得所有迭代中所有線程的摘要信息嗎?

回答

0

除非您想知道它出於好奇,否則如果您不創建過多的線程(即正確使用Executor框架或手動正確執行),則可能會認爲線程創建時間可以忽略不計。

關於由於鎖爭用而花費的時間,它隨應用程序負載而變化。獲取有用信息的最佳方式是在加載期望支持的加載的應用程序時執行線程轉儲,並查找處於BLOCKED狀態的線程和處於RUNNABLE狀態的線程。這樣你就會明白你的程序在鎖定爭用方面有多好。