我有一个多线程执行,我想跟踪并打印出执行时间,但是当我执行代码时,子线程比主执行花费的时间更长,因此输出不是可见,也不打印正确的值,因为它正在更早地终止。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