mysql多线程插入速度与不同数据库之间的比较
package ThreadInsetMysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
public class ThreadImportMysql {
private String url="jdbc:mysql://192.168.0.81:3306/mysqltest";
private String user="pmlf_hebei";
private String password="pmlf_hebei";
public Connection getConnect(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public void multiThreadImport( final int ThreadNum){
final CountDownLatch cdl= new CountDownLatch(ThreadNum);
long starttime=System.currentTimeMillis();
final int dataSize=60000;
for(int k=1;k<=ThreadNum;k++){
new Thread(new Runnable() {
@Override
public void run() {
Connection con=getConnect();
try {
con.setAutoCommit(false);//关闭事务的自动提交
System.out.println("关闭了事务自动提交设置");
Statement st=con.createStatement();
for(int i=1;i<=dataSize/ThreadNum;i++){
String uuid=UUID.randomUUID().toString();
st.addBatch("insert into demo_table(a,b) values('"+uuid+"','"+uuid+"')");
if (ThreadNum == 1) {
if (i % dataSize == 0) {
System.out.println("单线程提交数据库一次-----"+i+"--"+uuid);
st.executeBatch();
}
}
else {
if (i % (dataSize / ThreadNum) == 0) {
System.out.println("多线程提交数据库一次-----" + uuid);
st.executeBatch();
}
}
}//for
cdl.countDown();
con.commit();
} catch (Exception e) {
}finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}).start();
//内部类方法
}
try {
cdl.await();
long spendtime=System.currentTimeMillis()-starttime;
System.out.println( ThreadNum+"个线程花费时间:"+spendtime+"m秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ThreadImportMysql ti=new ThreadImportMysql();
// ti.multiThreadImport(1);
//ti.multiThreadImport(5);
// ti.multiThreadImport(8);
// ti.multiThreadImport(10);
//ti.multiThreadImport(20);
ti.multiThreadImport(100);
System.out.println("笔记本CPU数:"+Runtime.getRuntime().availableProcessors());
}
}
mySQLduo