//一个c3p0的数据库连接池的多线程测试
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Random;
import com.cn.wangk.db.DbUtil;
import com.cn.wangk.db.MyDbutil;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DbThread extends Thread {
private int ThreadNum = 0;
private ComboPooledDataSource ds;
public DbThread(int num,ComboPooledDataSource ds) {
ThreadNum = num;
this.ds = ds;
}
public void run() {
Random random = new Random();
System.out.println("线程"+ThreadNum+"启动");
int count = 0;
Connection connection = null;
try {
connection = ds.getConnection();
} catch (SQLException e2) {
e2.printStackTrace();
}
try {
connection.setAutoCommit(false);
while(count<30){
try {
int inum = random.nextInt(1000);
Thread.sleep(inum);
} catch (InterruptedException e) {
e.printStackTrace();
}
Statement stmt = connection.createStatement();
System.out.println("线程"+ThreadNum+",第“"+count+"”次插入数据");
stmt.execute("insert into test1 (name,cb)values('我是线程"+ThreadNum+",第“"+count+"”次插入数据!','"+ThreadNum+"')");
stmt.close();
count++;
}
if(ThreadNum==150)
connection.commit();
else
connection.rollback();
connection.setAutoCommit(true);
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
System.out.print(e1.getMessage());
}
System.out.print(e.getMessage());
}finally{
try {
if(connection !=null)
connection.close();
} catch (SQLException e) {
System.out.print(e.getMessage());
}
}
//System.out.println(ThreadNum);
}
/**
* @param args
*/
public static void main(String[] args) {
ComboPooledDataSource ds = new ComboPooledDataSource();
//truncate table test1
// TODO Auto-generated method stub
MyDbutil dbutil = MyDbutil.Open();
//测试多数据流
try {
dbutil.execute("truncate table test1");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 500; i++) {
DbThread dbThread = new DbThread(i,ds);
dbThread.start();
}
}
}
转载于:https://my.oschina.net/lovelong1/blog/5809