Package cn.hc.sort.thread;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.Semaphore;
/** * Signal Volume instance * Created by YHC on 2015/5/5.
* * Public class Semaphoretest {private static class Connection {private int id;
public int getId () {return id;
The public void setId (int id) {this.id = ID; } private static class Pool {private list<connection> idlepool = new arraylist<connection>
(32);
Private list<connection> Usedpool = new arraylist<connection> (32);
Private semaphore Semaphore=new Semaphore (32);
public void init () {//Initialize connection SYSTEM.OUT.PRINTLN ("Initialize connection pool ...");
for (int i = 0; i < i++) {Connection connection=new Connection ();
Connection.setid (i);
Idlepool.add (connection);
} /**** * Initialize connection * @return/public Connection get () {try{
SYSTEM.OUT.PRINTLN ("Get Connection object, number of connections:" +semaphore.availablepermits ());
Semaphore.acquire ();
Connection connection= idlepool.remove (0);
Usedpool.add (connection);
System.out.println ("Get Connected, id=" +connection.getid ());
return connection;
}catch (Exception e) {e.printstacktrace ();
return null; /** * FREE Connection * @param connection */public void release (Connection connection)
{try{System.out.println ("Free connections, number of connections available:" +semaphore.availablepermits ());
Usedpool.remove (connection);
Idlepool.add (connection);
SYSTEM.OUT.PRINTLN ("Release connection, id=" +connection.getid ()); }catch (Exception e) {E.printstackTrace ();
}finally {semaphore.release ();
}} public static void Main (string[] args) {semaphoretest semaphoretest=new semaphoretest ();
Final Pool pool=new Semaphoretest.pool ();
Pool.init ();
for (int i = 0; i < i++) {thread thread=new thread (new Runnable () {@Override
public void Run () {Connection Connection = Pool.get ();
TODO complex operations, loading data ... try {thread.sleep (2000);
catch (Interruptedexception e) {e.printstacktrace ();
}finally {//Release connection pool.release (connection);
}
}
});
Thread.Start ();
} System.out.println ("End");
}
}