由于项目中使用到ITesseract OCR文字提取,但每页提取文字大概需要一分钟时间,公司又不让用百度ocr。只能使用多线程提高读取效率。
在使用的过程中发现线程池调用线程时并未实现并发。
ExecutorService executor = Executors.newFixedThreadPool(3);
Map<Integer,String> map=new HashMap<>();
//pdfList存文件路径
try{
for (String path : pdfList) {
Future<Map<Integer, String>> future = executor.submit(new PngToStringThread(path, i));
map.putAll(future.get())
i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
原因:通过调用future.get()方法,当前线程会阻塞,直到获取到任务的执行结果. 修改后代码如下:
for (String path : pdfList) {
Future<Map<Integer, String>> future = executor.submit(new PngToStringThread(path, i));
futures.add(future);
i++;
}
executor.shutdown();
try {
for (Future<Map<Integer, String>> future : futures) {
map.putAll(future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
for (int j = 0; j < i; j++) {
result.append(map.get(j));
}