【发布时间】:2016-11-22 11:58:25
【问题描述】:
我有一个要求更新数据库中可用的 300 000 条记录。当我编写一个独立程序时,它需要 25-30 分钟来更新 5 000 条记录。所以完成所有记录可能需要 30 个小时。然后我想我会写一个多线程程序。我创建了 2 个线程,然后开始更新,它花费了相同的时间意味着 5k 条记录需要 30 分钟。
据我所知,我们正在使用线程来并发访问一个方法,在这种情况下它不会加速更新。
对于上述情况,我必须做些什么来减少时间。而多线程的实际用途是什么
class MyThread1 extends Thread{
public static String getTaskID(String PID)
{
String taskID = OurGenerator.orgPID(PID);
return taskID;
}
Connection con;
PreparedStatement pstmt;
BufferedReader bf;
MyThread1(Connection con,PreparedStatement pstmt){
this.con=con;
this.pstmt=pstmt;
try {
bf=new BufferedReader(new FileReader("D:/prod_review_sifid3.txt"));
}catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
public void run(){
String line;
try{
while (( line = bf.readLine()) != null)
{
String taskID = getTaskID(line);
pstmt.setString(1,taskID);
pstmt.setString(2,line);
pstmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class MyThread2 extends Thread{
public static String getTaskID(String PID)
{
String taskID = OurGenerator.orgPID(PID);
return taskID;
}
Connection con;
PreparedStatement pstmt;
BufferedReader bf;
MyThread2(Connection con,PreparedStatement pstmt){
this.con=con;
this.pstmt=pstmt;
try {
bf=new BufferedReader(new FileReader("D:/sifid_review2.txt"));
}catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
public void run(){
String line;
try{
while (( line = bf.readLine()) != null)
{
String taskID = getTaskID(line);
pstmt.setString(1,taskID);
pstmt.setString(2,line);
pstmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class SifuuidInsert {
public static void main(String ar[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("","","");
PreparedStatement pstmt=con.prepareStatement("update Taskdata set taskID=? where entryid=?");
MyThread1 first=new MyThread1(con,pstmt);
first.start();
MyThread2 second=new MyThread2(con,pstmt);
second.start();
}
}
【问题讨论】:
-
这真的取决于你的
run()方法中发生了什么。 -
字符串行; try{ while (( line = bf.readLine()) != null) { String sifID = getSIFID(line);//lines 表示一个 id //我从一个有 30 万个 id 的文本文件中读取该 id pstmt .setString(1,sifUUID); pstmt.setString(2,line); pstmt.executeUpdate(); } }catch(异常 e){ e.printStackTrace(); }
-
能否将代码添加到您的问题中?这样我们可以例如见范围。
-
嗨 @mad_manny 我添加了代码
-
每个线程都应该获得自己的连接并创建/使用自己的预处理语句。否则,在最好的情况下,线程在驱动程序处停止,在更坏的情况下,程序有未定义的行为 - 崩溃、部分更新、数据库数据损坏等。
标签: java multithreading