semaphore可以用于同步的控制。
semaphore.acquire()用于获取许可。(这个函数有阻塞效果)
semaphore.release()用于释放许可。
public class ConnectPool {
private ArrayList<Conn> pool = new ArrayList<Conn>();
private Semaphore semaphore = new Semaphore(3);
class Conn {
}
ConnectPool() {
pool.add(new Conn());
pool.add(new Conn());
pool.add(new Conn());
}
public Conn getConn() throws InterruptedException {
Conn c = null;
semaphore.acquire();
if (pool.size() > 0) {
synchronized (pool) {
c = pool.remove(0);
}
}
// System.out.println(Thread.currentThread().getName()+" get a conn " +
// c);
return c;
}
public void release(Conn c) {
pool.add(c);
// System.out.println(Thread.currentThread().getName()+" release a conn
// " + c);
semaphore.release();
}
public static void main(String[] args) throws InterruptedException {
ConnectPool cp = new ConnectPool();
System.out.println("当前的大小" + cp.pool.size());
for (int i = 0; i < 20; i++) {
new Thread() {
public void run() {
try {
Conn c =null;
c = cp.getConn();
System.out.println(Thread.currentThread().getName() + "链接上了....");
System.out.println("当前的大小" + cp.pool.size());
Thread.sleep(3000);
cp.release(c);
System.out.println(Thread.currentThread().getName() + "断开链接上了....");
System.out.println("当前的大小" + cp.pool.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
}