【发布时间】:2012-04-18 00:20:10
【问题描述】:
我有一个多线程执行,我想跟踪并打印出执行时间,但是当我执行代码时,子线程比主执行花费更长的时间,因此输出不可见,也不会打印正确的值,因为它提前终止了。
代码如下:
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);
}
我尝试了几种解决方案,例如 join()、wait() 和 notifyAll(),但都没有奏效。
我在 stackoverflow 上找到了这个 Q&A,它处理了我的问题,但是 join() 被忽略了,如果我放了
es.awaitTermination(timeout, TimeUnit.SECONDS);
实际上执行器服务从不执行线程。
仅在 ExecutorService 块中执行多线程并在最后完成主执行的解决方案是什么?
【问题讨论】:
-
我只会将
Runnable提交给ExecutorService,而不是调用join()或其他任何东西。您使用并发框架的方式似乎不正确。还要注意生成的线程是用户线程:守护线程不会阻止 JVM 退出。我很确定默认情况下线程是用户线程。
标签: java multithreading