java dbpool_java数据库连接池_方便自己学习

packagecom.pool;importjava.sql.Connection;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.atomic.AtomicInteger;/***类说明:测试并发1000次从池拿连接*/

public classDBPoolTest {static DBPool pool = new DBPool(10);//控制器:控制main线程将会等待所有Woker结束后才能继续执行

staticCountDownLatch end;public static void main(String[] args) throwsException {//线程数量

int threadCount = 50;

end= newCountDownLatch(threadCount);int count = 20;//每个线程的操作次数

AtomicInteger got = new AtomicInteger();//计数器:统计可以拿到连接的线程

AtomicInteger notGot = new AtomicInteger();//计数器:统计没有拿到连接的线程

for (int i = 0; i < threadCount; i++) {

Thread thread= new Thread(newWorker(count, got, notGot),"worker_"+i);

thread.start();

}

end.await();//main线程在此处等待

System.out.println("总共尝试了: " + (threadCount *count));

System.out.println("拿到连接的次数: " +got);

System.out.println("没能连接的次数: " +notGot);

}static class Worker implementsRunnable {intcount;

AtomicInteger got;

AtomicInteger notGot;public Worker(intcount, AtomicInteger got,

AtomicInteger notGot) {this.count =count;this.got =got;this.notGot =notGot;

}public voidrun() {while (count > 0) {try{//从线程池中获取连接,如果1000ms内无法获取到,将会返回null//分别统计连接获取的数量got和未获取到的数量notGot

Connection connection = pool.fetchConnection(1000);if (connection != null) {try{

connection.createStatement();

connection.commit();

}finally{

pool.releaseConnection(connection);

got.incrementAndGet();

}

}else{

notGot.incrementAndGet();

System.out.println(Thread.currentThread().getName()+"等待超时!");

}

}catch(Exception ex) {

}finally{

count--;

}

}

end.countDown();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值