一个c3p0的数据库连接池的多线程测试

//一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值