首页 > 解决方案 > java Future不一致的get()返回值

问题描述

请帮我。我不知道我在做什么了。

问题是 future.get() 的返回值;不一致。结果有时是 (valid and valid), (valid and null), (null and valid)

ExecutorService executorService = Executors.newFixedThreadPool(
        ConfigParameter.HTML_TO_PDF_CONVERTER_MAX_THREADS.getPropertyValue(20));
Set<Callable<String>> workers = new LinkedHashSet<>();

System.out.println("values to process: " + values.size());
for (String serviceId : values) {
    workers.add(new HtmlInvoiceNMIPdfWorker(dir, customer, serviceId, stmtno,
            html_invoice_id, groupno, htmlconverter_cmd, size));
}

System.out.println("Workers: " + workers.size());

// run threads
List<Future<String>> futures = executorService.invokeAll(workers);
System.out.println("Futures.size(): " + futures.size());

// get worker results
for (Future<String> future : futures) {
    System.out.println("Futures: " + future.get());
    String file = future.get();

    if (!StringUtil.isNullOrEmpty(file)) {
        System.out.println("filenames.add(file): " + file);
        filenames.add(file);
    } else {
        // do nothing
    }

}

executorService.shutdown();

打印结果之一:

value to process: 2
Workers: 2
Futures.size(): 2
Futures: null
Futures: 32000_1367_20181119182612.pdf
filenames.add(file): 32000_1367_20181119182612.pdf

我是线程新手。我已经阅读了多个 stackoverflow 问题,但仍然不知道原因。

编辑:添加了可调用的一部分,因为它是一个很大的方法。getInvoice() 根据设置从数据库中组装发票的 html 部分。然后 HTML 将转换为 PDF 以供下载。

String html="<html>";
html += "<head>";
html += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
html += "<style>@font-face {font-family: 'ocr-b_10_btregular'; src: url('assets/font/tt0646m-webfont.woff2') format('woff2'), url('assets/font/tt0646m-webfont.woff') format('woff'); font-weight: normal; font-style: normal;}</style>";
html += "</head>";
html += "<body>";
html += getInvoice(custno, stmtno,nmiServiceId, html_invoice_id, wsReplacePath, groupno);
html += "</body>";
return convertToPDF(html,destination,custno,stmtno,html_invoice_id,groupno,null,cmd);

标签: javamultithreadingfutureexecutorservice

解决方案


推荐阅读