我想每秒插入数据库4个数据。同时让每个线程等待并一起唤醒。然后每个线程进入休眠状态1秒钟,整个过程将重复。我面临的问题是这里DATA值没有增加,在运行程序之后,它会继续将数据插入数据库,直到强制停止/终止,插入0后,下一个数据显示2.如何解决这个问题?
以下是我得到的输出
08-JUL-16 07.43.42.721000 AM 0
08-JUL-16 07.43.42.731000 AM 2
08-JUL-16 07.43.42.731000 AM 2
08-JUL-16 07.43.42.731000 AM 2
08-JUL-16 07.43.42.731000 AM 2
.
.
.
08-JUL-16 07.43.43.815000 AM 2
08-JUL-16 07.43.43.815000 AM 2
08-JUL-16 07.43.43.825000 AM 2
.
.
这是我的代码
public class TestMainConnection {
public static void main(String[] args) {
Thread t1=new Thread(new TestingThread(),"t1");
Thread t2=new Thread(new TestingThread(),"t2");
Thread t3=new Thread(new TestingThread(),"t3");
Thread t4=new Thread(new TestingThread(),"t4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
public class TestingThread implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
doDBProcessing();
}
catch(InterruptedException e){
System.out.println(e);
}
}
private void doDBProcessing() throws InterruptedException {
Connection conn=null;
PreparedStatement pstmt;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/xe","SYSTEM","sd");
String insertQuery = "Insert into k(workdate,data) values(?,?)";
pstmt = conn.prepareStatement(insertQuery);
for(int i=0;i<1000;i++) {
pstmt.setTimestamp(1, getCurrentTimeStamp());
pstmt.setLong(2, i);
i=pstmt.executeUpdate();
}
System.out.println("Data Successfully Uploaded");
pstmt.close();
conn.commit();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
}