java多线程读取文件并插入数据库
出现进程不同步,读取的行号出现重复等错误,求大神指导。代码如下:
public class InsertThread extends Thread {
BufferedReader buff;
private static volatile int count=0;
InsertThread(BufferedReader br) throws Exception{
buff=br;
Class.forName("com.mysql.jdbc.Driver");
}
//同步代码块
private synchronized String getLine(BufferedReader bufferedReader) throws IOException {
String lineString=bufferedReader.readLine();
count++;
System.out.println(count);
return lineString;
}
@Override
public void run() {
String line=null;
try {
String dbUrl = "jdbc:mysql://localhost:8066/mycat_test";
dbUrl+="?useServerPrepStmts=false&rewriteBatchedStatements=true";
Connection conn = DriverManager.getConnection(dbUrl, "test", "test");
conn.setAutoCommit(false);
String sql="insert into onetable(RowID,TableName,TupleNum,PropertyName,ElementValue)" +
" values (next value for MYCATSEQ_GLOBAL,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
while((line=getLine(buff))!=null){
synchronized (line) {
String[] arrtest = line.split("\\|");
for(int i=0;i<arrtest.length;i++){
pstmt.setInt(1, 1);
pstmt.setInt(2, count);
pstmt.setInt(3, 101+i);
pstmt.setString(4, arrtest[i]);
pstmt.addBatch();
}
}
}
System.out.println(count);
pstmt.executeBatch();
conn.commit();
conn.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}