我正在处理一个从 .csv 文件中读取项目并将它们写入远程数据库的程序。我正在尝试对程序进行多线程处理,为此我创建了 2 个具有不同连接的进程线程。为此,将 .csv 文件读入缓冲阅读器,并处理缓冲阅读器的内容。但是,线程似乎一直在复制数据(将每个元组的两个副本写入数据库)。
我一直在试图弄清楚如何在 Java 中对缓冲区进行互斥,而我能想到的最接近的事情是优先级队列。
我的问题是,您可以使用缓冲阅读器将文件逐行读入优先级队列吗?IE
public void readFile(Connection connection) {
BufferedReader bufReader = null;
try{
bufReader = new BufferedReader(new FileReader(RECS_FILE));
bufReader.readLine(); //skip header line
String line;
while((line = bufReader.readLine()) != null) {
//extract fields from each line of the RECS_FILE
Pattern pattern = Pattern.compile( "\"([^\"]+)\",\"([^\"]+)\",\"([^\"]+)\",\"([^\"]+)\"");
Matcher matcher = pattern.matcher(line);
if(!matcher.matches()) {
System.err.println("Unexpected line in "+RECS_FILE+": \""+line+"\"");
continue;
}
String stockSymbol = matcher.group(1);
String recDateStr = matcher.group(2);
String direction = matcher.group(3);
String completeUrl = matcher.group(4);
//create recommendation object to populate required fields
// and insert it into the database
System.out.println("Inserting to DB!");
Recommendation rec = new Recommendation(stockSymbol, recDate, direction, completeUrl);
rec.insertToDb(connection);
}
} catch (IOException e) {
System.err.println("Unable to read "+RECS_FILE);
e.printStackTrace();
} finally {
if(bufReader != null) {
try{
bufReader.close();
} catch (IOException e) {
}
}
}
}
您会看到缓冲阅读器用于读取 .csv 文件。有没有办法在函数外部设置优先级队列,以便缓冲读取器将元组放入优先级队列中,然后每个程序线程访问优先级队列?