A count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. The thread that gets the semaphore can enter the code or wait. Obtain and release access licenses through Acquire () and release ().
Example: If you are designing a database reader, the person using the program is more tentative 20, but also only allow 5 clients to use the program to the database operation, only before the release can be used later programs
The pseudo code is as follows:
Import java.util.concurrent.*;/** * by LV Xiao long **/ Public classApp { Public Static voidMain (string[] args) {//thread PoolExecutorservice exec =Executors.newcachedthreadpool (); //impersonation can only be accessed by 5 clients at a timeFinal Semaphore semp =NewSemaphore (5); //simulate 20 Client access for(intindex =0; Index < -; index++) {FinalintNO =index; Runnable Run=NewRunnable () { Public voidrun () {Try { //obtaining a licenseSemp.acquire (); System. out. println ("Accessing:"+NO); Thread.Sleep ((Long) (Math.random () *10000)); //after the access, release, if the following statement is masked, the console can only print 5 records, and then the thread has been blockedsemp.release (); } Catch(Interruptedexception e) {}}; Exec.execute (run); } //exit thread poolExec.shutdown (); }}
Introduction and use of Java semaphore