1.SqlConnectImpl? 數(shù)據(jù)庫的連接
public class SqlConnectImplimplements Connection {
/*拿一個(gè)數(shù)據(jù)庫連接*/
public static final Connection fetchConnection() {
return new SqlConnectImpl();
}
}
2.DBPool? ?連接池的實(shí)現(xiàn)
/**
* 類說明:連接池的實(shí)現(xiàn)
*/
public class DBPool {
private static LinkedListpool =new LinkedList();
public DBPool(int initialSize) {
if (initialSize >0) {
for (int i =0; i < initialSize; i++) {
pool.addLast(SqlConnectImpl.fetchConnection());
}
}
}
//? ? 釋放連接
public void releaseConnection(Connection connection) {
if (connection !=null) {
synchronized (pool) {
pool.addLast(connection);
pool.notifyAll();
}
}
}
// 在mills內(nèi)無法獲取到連接挪钓,將會(huì)返回null
public Connection fetchConnection(long mills)throws InterruptedException {
//TODO
synchronized (pool) {
if (mills <0) {
while (pool.isEmpty()) {
pool.wait();
}
return pool.removeFirst();
}else {
//超時(shí)時(shí)刻
long future = System.currentTimeMillis() + mills;
//超時(shí)時(shí)長(zhǎng)
long remaining = mills;
while (pool.isEmpty() && remaining >0) {
pool.wait(remaining);
//重新計(jì)算等待時(shí)長(zhǎng)
remaining = future - System.currentTimeMillis();
}
Connection connection =null;
if (!pool.isEmpty()) {
connection =pool.removeFirst();
}
return connection;
}
}
}
}
3.DBPoolTest? 最后測(cè)試運(yùn)行
public class DBPoolTest {
static DBPoolpool? =new DBPool(10);
// 控制器:控制main線程將會(huì)等待所有Woker結(jié)束后才能繼續(xù)執(zhí)行
static CountDownLatchend;
public static void main(String[] args)throws Exception {
// 線程數(shù)量
int threadCount =50;
end =new CountDownLatch(threadCount);
int count =20;//每個(gè)線程的操作次數(shù)
AtomicInteger got =new AtomicInteger();//計(jì)數(shù)器:統(tǒng)計(jì)可以拿到連接的線程
AtomicInteger notGot =new AtomicInteger();//計(jì)數(shù)器:統(tǒng)計(jì)沒有拿到連接的線程
for (int i =0; i < threadCount; i++) {
Thread thread =new Thread(new Worker(count, got, notGot), "worker_"+i);
thread.start();
}
end.await();// main線程在此處等待
System.out.println("總共嘗試了: " + (threadCount * count));
System.out.println("拿到連接的次數(shù):? " + got);
System.out.println("沒能連接的次數(shù): " + notGot);
}
static class Workerimplements Runnable {
int? ? count;
AtomicIntegergot;
AtomicIntegernotGot;
public Worker(int count, AtomicInteger got,
AtomicInteger notGot) {
this.count = count;
this.got = got;
this.notGot = notGot;
}
public void run() {
while (count >0) {
try {
// 從線程池中獲取連接夯巷,如果1000ms內(nèi)無法獲取到,將會(huì)返回null
? ? ? ? ? ? ? ? ? ? // 分別統(tǒng)計(jì)連接獲取的數(shù)量got和未獲取到的數(shù)量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()
+"等待超時(shí)!");
}
}catch (Exception ex) {
}finally {
count--;
}
}
end.countDown();
}
}
}
以上內(nèi)容僅代表個(gè)人學(xué)習(xí)的見解累奈,希望可以為大家提供一個(gè)學(xué)習(xí)參考