目前我的代碼一個接一個地爲多個核心實例化一個類,但是我想創建一個循環來實例化任意數量的核心的類檢測器(),並行運行。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加入之前,你甚至創建過程1. –
謝謝,我會與校正更新後 - 我認爲現在的代碼工作,但如果你可以檢查這將是更讚賞 – Adam