我正在用 Java 编写一个我想暂停和恢复的多线程应用程序。
线程正在逐行读取文件,同时查找与模式匹配的行。它必须在我暂停线程的地方继续。为了读取文件,我将 BufferedReader 与 InputStreamReader 和 FileInputStream 结合使用。
fip = new FileInputStream(new File(*file*));
fileBuffer = new BufferedReader(new InputStreamReader(fip));
我使用这个 FileInputStream 因为我需要文件指针作为文件中的位置。
在处理这些行时,它将匹配的行写入 MySQL 数据库。要在线程之间使用 MySQL 连接,我使用 ConnectionPool 来确保只有一个线程正在使用一个连接。
问题是当我暂停线程并恢复它们时,一些匹配的行就消失了。我还尝试从偏移量中减去缓冲区大小,但它仍然存在同样的问题。
什么是解决这个问题的好方法或者我做错了什么?
更多细节:
循环
// Regex engine
RunAutomaton ra = new RunAutomaton(this.conf.getAuto(), true);
lw = new LogWriter();
while((line=fileBuffer.readLine()) != null) {
if(line.length()>0) {
if(ra.run(line)) {
// Write to LogWriter
lw.write(line, this.file.getName());
lw.execute();
}
}
}
// Loop when paused.
while(pause) { }
}
计算文件中的位置
// Get the position in the file
public long getFilePosition() throws IOException {
long position = fip.getChannel().position() - bufferSize + fileBuffer.getNextChar();
return position;
}
将其放入数据库
// Get the connector
ConnectionPoolManager cpl = ConnectionPoolManager.getManager();
Connector con = null;
while(con == null)
con = cpl.getConnectionFromPool();
// Insert the query
con.executeUpdate(this.sql.toString());
cpl.returnConnectionToPool(con);