java代码多线程批量插⼊数据
l.dict;
import org.apache.ibatis.session.SqlSession;
port.db.DbFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import urrent.CountDownLatch;
import urrent.ExecutorService;
import urrent.Executors;
/
**
* @Auther: pccw
* @Date: 2018/10/29 17:45
* @Description:
*/
/*
往⾃⼰本地mysql 当中插⼊10W条记录
*/
public class TestTwo {
public static void main(String args[]) throws SQLException {
SqlSession sqlSession = DbFactory.Open(DbFactory.FORM);
/
/ insert(sqlSession);
insertTwo(sqlSession);
}
// 多线程案例使⽤fix线程规定为5个
public static void insertTwo(SqlSession sqlSession) throws SQLException {
Connection conn = Connection();
// 开始时间
Long begin = new Date().getTime();
final StringBuffer suffix = new StringBuffer();
// sql前缀
String prefix = "INSERT INTO test_dict (code,name) VALUES ";
/
/ 设置事务为⾮⾃动提交
conn.setAutoCommit(false);
// ⽐起st,pst会更好些
PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");//准备执⾏语句
final CountDownLatch count = new CountDownLatch(5); //相当线程执⾏计时器,await()让线程等待,⽤countDown()消初始化数量。当数量等于0时线程唤醒        ExecutorService fixedThreadPool = wFixedThreadPool(5); //线程池
synchronized (fixedThreadPool) {
for (int i = 1; i <= 5; i++) {
final int index = i;
if (i == 1) {
@Override
public void run() {
for (int j = 1; j < 10; j++) {
// 构建SQL后缀
suffix.append("(" + j + "," + "'0000" + j + "'),");
}
}
});
} else if (i == 2) {
@Override
public void run() {
for (int j = 10; j < 100; j++) {
// 构建SQL后缀
suffix.append("(" + j + "," + "'000" + j + "'),");
}
}
});
} else if (i == 3) {
@Override
public void run() {
for (int j = 100; j < 1000; j++) {
// 构建SQL后缀
suffix.append("(" + j + "," + "'00" + j + "'),");
}
}
});
} else if (i == 4) {
@Override
public void run() {
for (int j = 1000; j < 10000; j++) {
// 构建SQL后缀
suffix.append("(" + j + "," + "'0" + j + "'),");
}
}
});
} else {
@Override
public void run() {
for (int j = 10000; j <= 99999; j++) {
// 构建SQL后缀
suffix.append("(" + j + "," + "'" + j + "'),");
}
}
});
}
}
}
try {
count.await();
// 构建完整SQL
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// 添加执⾏SQL
pst.addBatch(sql);
// 执⾏操作
// 提交事务
connmit();
/
/ 头等连接
pst.close();
conn.close();
// 结束时间
Long end = new Date().getTime();
System.out.println("10万条数据插⼊花费时间 : " + (end - begin)  + " ms");            System.out.println("插⼊完成");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
fixedThreadPool.shutdown();
}
}
// 测试使⽤ fetch 按照指定规格读取数据
java多线程入门}