The semaphore of the operating system is a very important concept and has been applied in Process Control. The Semaphore of the Java concurrent library can easily control semaphores. Semaphore can control the number of resources that can be accessed at the same time. acquire () can obtain a license. If not, wait, while release () release a license. For example, in Windows, you can set the maximum number of client accesses to shared files. Semaphore maintains the current number of accesses and provides a synchronization mechanism to control the number of simultaneous accesses. In the data structure, the linked list can store "unlimited" nodes and use Semaphore to implement a limited-size linked list. In addition, the ReentrantLock function can be implemented, but the implementation should be more responsible and the code should be more complex. The following is a simulation of a connection pool that controls up to 50 threads to access at a time.
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 <500) {I ++; new TestSemaphore (). start (); try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();}}} /*** controls the number of classes simultaneously accessed by a resource. At the end of the same time, there can only be 50 accesses */static Semaphore semaphore = new Semaphore (50 ); static int timeout = 500; public void run () {try {Object connec = getConnection (); System. out. println ("get a connection" + connec); Thread. sleep (300); 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 Permission */boolean getAccquire = semaphore. tryAcquire (timeout, TimeUnit. MILLISECONDS); if (getAccquire) {return UUID. randomUUID (). toString () ;}} catch (InterruptedException e) {e. printStackTrace ();} throw new IllegalArgumentException ("timeout ");}}