我正在尝试构建一个工具,该工具在进行一些字符串转换后将读取文本文件并发布文本。
该工具逐行读取文件并填充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。我该如何解决?基本上,这两种方法应该并行执行。
答案 0 :(得分:1)
只需在新线程(Main类中的第5行)上启动messagePublisher:
new Thread(()->tool.initMessagePublish()).start();
它应该可以解决您的问题。