Semaphore literal translation is a semaphore, its function is better understood, is to set a number of permits by the constructor, and then through the acquire method to obtain permission, release method releases the license. It also has Tryacquire and acquireuninterruptibly methods that can be selected according to your needs.
The following is a simulation of a connection pool, control can only have a maximum of 50 threads at a time, the main thread creates a child thread per millisecond, a connection pool of 50 licenses, each get connected sub-thread ball 300ms, connection wait timeout 500ms.
[Java]import java.util.uuid;import Java.util.concurrent.semaphore;import Java.util.concurrent.timeunit;public Class Testsemaphore extends Thread {public static void main (string[] args) {int i = 0;while (i <) {I++;new Testsema Phore (). Start (); try {thread.sleep (1);} catch (Interruptedexception e) {e.printstacktrace ();}}} /** * Control the number of simultaneous access to a resource class control at the same time there can be only 50 access */static Semaphore Semaphore = new Semaphore (a); static int timeout = 500;public vo ID run () {try {Object Connec = getconnection (); System.out.println ("Get a Connection" + Connec); Thread.Sleep (+); releaseconnection (Connec);} catch (Interruptedexception e) {e.printstacktrace ();}} public void Releaseconnection (Object connec) {/* release license */semaphore.release (); System.out.println ("Release a Connection" + Connec); Public Object getconnection () {try {* * * get license */boolean getaccquire = Semaphore.tryacquire (timeout, timeunit.milliseconds) ; if (Getaccquire) {return Uuid.randomuuid (). toString ();}} catch (Interruptedexception e) {e.printstacktrace ();} throw new IllegalarguMentexception ("timeout");}} [/java]
Java concurrent Programming-semaphores