我正在處理從.csv文件中讀取項目的程序,並將它們寫入遠程數據庫。我正在嘗試多線程程序,爲此我創建了2個具有不同連接的進程線程。爲此,將.csv文件讀入緩衝讀取器,並處理緩衝讀取器的內容。但是,線程似乎繼續複製數據(將每個元組的兩個副本寫入數據庫)。緩衝閱讀器和優先級隊列一起工作?
我一直在試圖找出如何互斥在Java中的緩衝器,並且我能想出最接近的事是一個優先級隊列。
我的問題是,你可以使用一個緩衝的閱讀器來閱讀一個文件分割成線優先級隊列線? I.E.
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文件。有沒有辦法在函數之外設置一個優先級隊列,以便緩衝讀取器將元組放入優先級隊列,然後每個程序線程訪問優先級隊列?