2014-03-31 38 views
0

目前我的代碼一個接一個地爲多個核心實例化一個類,但是我想創建一個循環來實例化任意數量的核心的類檢測器(),並行運行。Java在一個循環中實例化一個類

int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads 

    detectors.getStartingConditions(); 

     long startTime = System.currentTimeMillis(); 

     detectors core1= new detectors(); 
     detectors core2= new detectors(); 
     detectors core3= new detectors(); 
     //etc 

     core1.start(); 
     core2.start(); 
     core3.start(); 
     //etc 

     try 
     { // wait for completion of all thread and then sum 
      core1.join(); 
      core2.join(); 
      core3.join(); 
      //etc 
     } 
    catch(InterruptedException IntExp) {}   

     long endTime = System.currentTimeMillis(); 

     System.out.println("That took " + (endTime - startTime) + " milliseconds"); 

我在溶液嘗試:

我創建的對象的陣列如下但是處理器內核上運行一個,而不是同時在另一個之後。

編輯:核心現在同時運行。

int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads 
detectors[] theCores = new detectors[processors]; 

    detectors.getStartingConditions(); 

     long startTime = System.currentTimeMillis(); 

     for(int i = 0; i <= processors-1; i++){ 
     theCores[i] = new detectors(); 
     theCores[i].start(); 
     } 

     for(int i = 0; i <= processors-1; i++){ 
     try{ 
     theCores[i].join();} 

     catch(InterruptedException IntExp) {} 
     } 

     long endTime = System.currentTimeMillis(); 

     System.out.println("That took " + (endTime - startTime) + " milliseconds"); 
+0

你等待的過程0加入之前,你甚至創建過程1. –

+0

謝謝,我會與校正更新後 - 我認爲現在的代碼工作,但如果你可以檢查這將是更讚賞 – Adam

回答

1

您的代碼創建線程並在創建下一個線程之前將其加入。這會導致順序執行。您必須改用兩個循環。第一個循環創建所有線程,而第二個循環連接所有線程。

for (int i = 0; i < processors; ++i) { 
    theCores[i] = new detectors(); 
    theCores[i].start(); 
} 

for (int i = 0; i < processors; ++i) { 
    try { 
     theCores[i].join(); 
    } catch (InterruptedException ie) { 
     RuntimeException re = new RuntimeException("unsupported interruption", ie); 
     for (++i; i < processors; ++i) { 
      try { 
       theCores[i].join(); 
      } catch (InterruptedException e) { 
       re.addSuppressed(e); 
      } 
     } 
     throw re; 
    } 
} 
+0

謝謝,一個微不足道的錯誤,我的錯誤。是否需要在第二個循環中使用try和catch代碼? – Adam

+0

我已經添加了拋出InteruptedException現在的整個方法,但最好的做法是抓住它?新解決方案代碼中的catch語句應該移到哪裏? – Adam

+0

我已經添加了正確處理_InterruptedException_的代碼。 – nosid