什么?我正在尝试构建一个在执行一些字符串转换后将读取文本文件并发布文本的工具。如何?该工具逐行读取文件并填充LinkedBlockingQueue。同时,我启动多个线程,然后将每个线程从LBQ接收一条消息,进行一些处理并发布它们。主要的private static LinkedBlockingQueue<String> lbQueue = new LinkedBlockingQueue<>();private static Boolean keepPublisherActive = Boolean.TRUE;public static void main(String[] args) { try { tool.initMessagePublish(); tool.searchUsingScanner(); } catch (Exception ex) { logger.error("Exception in Tool Main() " + ex.toString()); throw ex; }}文件阅读器private void searchUsingScanner() { Scanner scanner = null; try { scanner = new Scanner(new File(LOG_FILE_PATH)); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (StringUtils.isNotBlank(line)) { lbQueue.offer(line); } } } catch (Exception e) { logger.error("Error while processing file: " + e.toString()); } finally { try { if (scanner != null) { scanner.close(); } // end thread execution keepPublisherActive = false; } catch (Exception e) { logger.error("Exception while closing file scanner " + e.toString()); throw e; } } }多线程发布者 private void initMessagePublish() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(6); try { while (keepPublisherActive || lbQueue.getSize() > 0) { service.execute(messagePublisher); // messagePublisher implements Runnable } } catch (Exception ex) { logger.error("Multi threaded message publish failed " + ex.toString()); throw ex; } finally { service.shutdown(); }}问题调用initMessagePublish()的初衷是,发布者无需等待开始从文件中读取所有行就可以开始发布。一旦在LBQ中可用,它应该立即开始发布。但是使用当前的实现,该控件永远不会出现在initMessagePublish之外,而不会启动searchUsingScanner。我该如何解决?基本上,这两种方法应并行执行。
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
只需在新线程(Main类中的第5行)上启动messagePublisher:
new Thread(()->tool.initMessagePublish()).start();
它应该可以解决您的问题。
添加回答
举报
0/150
提交
取消