java多线程读取文件并插入数据库

xihua1244914259 2015-04-03 09:56:53
出现进程不同步,读取的行号出现重复等错误,求大神指导。代码如下:
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();
}
}
}
...全文
680 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiar2046 2016-02-27
  • 打赏
  • 举报
回复
这个synchronized (line) 没有用啊,line对象每个线程都各有一个,加不加锁没啥用。。。 只是实现了读取文件的同步,写数据库并没有实现。应该对写方法进行同步加锁。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧