Direction
Semaphore can maintain the number of threads currently accessing itself and provides a synchronization mechanism. You can use semaphore to control the number of threads that access resources concurrently, for example, to implement the number of concurrent accesses allowed for a file.
Semaphore implementation of the function is similar to the print shop has 5 printers, if there are 10 people to print files, then also can have a few people print it? At the same time, only 5 people can occupy the printer, and when any of the 5 people use it, one of the other 5 people waiting for it will be occupied. The other 5 people who are waiting can be given a chance at random, or they can be given an opportunity in the order of first served, depending on the parameter options passed in when constructing the semaphore object.
The semaphore object of a single semaphore can implement a mutex function, and it can be a thread that obtains a "lock", and another thread releases the "lock", which can be applied to some occasions of deadlock recovery.
Example
1 Public classSemaphoretest {2 Public Static voidMain (string[] args) {3Executorservice Service =Executors.newcachedthreadpool ();4 FinalSemaphore SP =NewSemaphore (3);5 for(inti=0;i<10;i++){6Runnable Runnable =NewRunnable () {7 Public voidrun () {8 Try {9 Sp.acquire ();Ten}Catch(interruptedexception E1) { One e1.printstacktrace (); A } -SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + -"Enter, current already" + (3-sp.availablepermits ()) + "concurrency"); the Try { -Thread.Sleep ((Long) (Math.random () *10000)); -}Catch(interruptedexception e) { - e.printstacktrace (); + } -SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + +"Leaving Soon"); A sp.release (); at //The following code is sometimes executed inaccurately because it does not synthesize atomic units with the above code -SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + -"Has left, currently has" + (3-sp.availablepermits ()) + "concurrency"); - } - }; - Service.execute (runnable); in } - } to}
Semaphore realization of signal lights