我有一個多線程執行,我想跟蹤並打印出執行時間,但是當我執行代碼時,子線程比主執行花費的時間更長,因此輸出不是可見,也不打印正確的值,因爲它正在更早地終止。Java主類在執行線程之前結束
下面是代碼:
public static void main(String[] args) throws CorruptIndexException, IOException, LangDetectException, InterruptedException {
/* Initialization */
long startingTime = System.currentTimeMillis();
Indexer main = new Indexer(); // this class extends Thread
File file = new File(SITES_PATH);
main.addFiles(file);
/* Multithreading through ExecutorService */
ExecutorService es = Executors.newFixedThreadPool(4);
for (File f : main.queue) {
Indexer ind = new Indexer(main.writer, main.identificatore, f);
ind.join();
es.submit(ind);
}
es.shutdown();
/* log creation - code I want to execute when all the threads execution ended */
long executionTime = System.currentTimeMillis()-startingTime;
long minutes = TimeUnit.MILLISECONDS.toMinutes(executionTime);
long seconds = TimeUnit.MILLISECONDS.toSeconds(executionTime)%60;
String fileSize = sizeConversion(FileUtils.sizeOf(file));
Object[] array = {fileSize,minutes,seconds};
logger.info("{} indexed in {} minutes and {} seconds.",array);
}
我嘗試了幾種解決方案,比如加入(),wait()和notifyAll的(),但沒有一次成功。
我發現這個計算器其中Q&A對待我的問題,但join()方法將被忽略,如果我把
es.awaitTermination(超時,TimeUnit.SECONDS);
實際上執行程序服務從不執行線程。
哪一種解決方案只能在ExecutorService塊中執行多線程,並在最後執行主執行?
我只需將'Runnable'提交給'ExecutorService',而不是調用'join()'或其他任何東西。您使用併發框架的方式似乎不正確。還要注意生成的線程是用戶線程:守護進程線程不會阻止JVM退出。我很確定,默認情況下,線程是用戶線程。 – 2012-04-18 02:50:53