Semaphore can maintain the number of threads currently accessing itself and provides a synchronization mechanism. using semaphore, you can control the number of threads that access resources concurrently (that is, allow n tasks to access the resource at the same time), such as implementing the number of concurrent accesses allowed by a file.
Semaphore implementation of the function is similar to the toilet has 5 pits, if there are 10 people to the toilet, then how many people to go to the toilet? At the same time only 5 people can occupy, when any one of the 5 people out of the way, one of the other 5 waiting for another to occupy.
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.
Package Java_thread;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.semaphore;public class Semaphoretest {public static void main (string[] args) {Executorservice Service = Executors.newcachedthreadpool (); final Semaphore sp = new Semaphore (3); for (int i=0;i<10;i++) {Runnable runnable = new Runnable () {public void run () {try {sp.acquire ();} catch (Interruptedexception E1) {e1.printstacktrace ()} SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Enter, current already" + (3-sp.availablepermits ()) + "concurrency"); try { Thread.Sleep ((Long) (Math.random () *10000));} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Threads" + thread.currentthread (). GetName () + "going Away"); Sp.release ();//The following code sometimes does not perform accurately, Because it does not synthesize atomic units with the above code System.out.println ("thread" + thread.currentthread (). GetName () + "left, current already" + (3-sp.availablepermits ()) + "concurrency");}; Service.execute (runnable);}}}
Java multithreaded--semaphore semaphore