最近写了一个多线程向数据库写入批量数据的程序。
程序实现功能:
1. 单线程向Mysql数据库表中插入20万数据记录。
2 . 启用四个线程负责向四张不同的表分别插入5万数据。
3 . 分别记录插入数据时间并进行对比。
程序代码:
一 连接池类 ConnectionPool
该类负责数据库连接池的创建,每个线程要连接数据库时直接从数据库连接池取得连接:
package com.mysql;
import java.util.ArrayList;
public class ConnectionPool {
private String user="";
private String password="";
final static String jdbcDriver="com.mysql.jdbc.Driver";
private String url="";
private int maxConnection=10;
private ArrayList<ConnectionClass> connections=null;
public ConnectionPool(String url,String user,String password)
{
this.setUrl(url);
this.setUser(user);
this.setPassword(password);
createConnections();
}
/***
* create connections in connection pool
*/
private void createConnections()
{
if(connections!=null)
return;
else
{
connections = new ArrayList<ConnectionClass>();
for(int i=0;i<maxConnection;i++)
{
ConnectionClass t=new ConnectionClass(jdbcDriver,url,user,password);
if(t!=null)
{
connections.add(t);
}
}
}
}
/**
* get free connection
* @return
*/
public synchronized ConnectionClass findFreeConnection() // 线程每次获取空闲连接是要实现同步
{
ConnectionClass t=null;
int i=0;
for(i=0;i<maxConnection;i++)
{
t=connections.get(i);
if(t.isBusy()==false)
break;
}
if(i<maxConnection)
t.setBusy(true);
return t;
}
public int getMaxConnection() {
return maxConnection;
}
public void setMaxConnection(int maxConnection) {
this.maxConnection = maxConnection;
}
public ArrayList<ConnectionClass> getConnections() {
return connections;
}
public void setConnectio