package com.simonjia.web.index.service;
import com.simonjia.web.index.InsertThread;
import java.util.concurrent.CountDownLatch;
/**
* @Author: SimonHu
* @Date: 2020/7/16 9:47
* @Description:
*/
public class InsertTest {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(10);
long s = System.currentTimeMillis();
for (int i = 1; i <= 10; i++) {
InsertThread insertThread = new InsertThread(latch);
insertThread.start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long e = System.currentTimeMillis();
System.out.println("--------------------总耗时-----------" + (e - s)/1000 + "s");
}
}
package com.simonjia.web.index;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
/**
* @Author: SimonHu
* @Date: 2020/7/16 9:41
* @Description:
*/
public class InsertThread extends Thread {
private CountDownLatch latch;
public InsertThread(CountDownLatch latch) {
this.latch = latch;
}
public InsertThread() {
super();
}
@Override
public void run() {
//数据库连接地址
String url = "jdbc:mysql://localhost:3306/sss?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false";
String name = "com.mysql.jdbc.Driver";
String user = "root";
String password = "123456";
Connection conn = null;
try {
Class.forName(name);
conn = DriverManager.getConnection(url, user, password);
//关闭自动提交
conn.setAutoCommit(false);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long begin = System.currentTimeMillis();
System.out.println("当前线程名称----START--------" + Thread.currentThread().getName());
String sql = "INSERT INTO teachers (t_name,t_password,sex,description,pic_url,school_name,regist_date,remark) VALUES(?,?,?,?,?,?,?,?)";
try {
conn.setAutoCommit(false);
PreparedStatement pst = conn.prepareStatement(sql);
//编写事务
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 100000; j++) {
pst.setString(1, "teacher" + i * j);
pst.setString(2, "12223444");
pst.setString(3, "男");
pst.setString(4, "教师");
pst.setString(5, "www.bbb.com");
pst.setString(6, "java大学");
pst.setString(7, "2016-08-16 14:43:26");
pst.setString(8, "你好啊");
pst.addBatch();//批量添加信息
}
// 执行批量操作
pst.executeBatch();
// 提交事务
conn.commit();
}
pst.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
latch.countDown();
}
// 结束时间
Long end = System.currentTimeMillis();
// 耗时
System.out.println("当前线程名称------END------" + Thread.currentThread().getName());
System.out.println("100万条数据插入花费时间 : " + (end - begin) / 1000 + " s" + " 插入完成");
}
}