Semaphore can maintain the number of threads currently accessed, and provides a synchronization mechanism. Semaphore can be used to control the number of threads simultaneously accessing resources. For example, the number of concurrent threads allowed by a file is realized. the functions implemented by Semaphore are similar to that implemented by a total of five moukeng (new Semaphore (5) in the restroom. A total of 10 persons (10 threads) are added to the restroom, at the same time, only five people can occupy the resources. When one of the five people is occupied, the release () method is used ), among the other five persons waiting, one can use the (acquire () method ). in addition, the five waiting persons can obtain the opportunity at random or in the order of first-in-second arrival, depending on the parameter options passed in by the constructor. public Semaphore (int permits, boolean fair) the Semaphore object of a single Semaphore can implement the mutex lock function, and the lock can be obtained by one thread, and then released by another thread, that is to say, a thread can release the lock, even though it does not get the permit, which can be used to apply the deadlock recovery.
Public class SemaphoreTest {public static void main (String [] args) {ExecutorService service = Executors. newCachedThreadPool (); final Semaphore sp = new Semaphore (3, true); 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" + (3-sp. availablePermits () + "concurrent"); try {Thread. sleep (long) (Math. random () * 10000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("Thread" + Thread. currentThread (). getName () + "coming soon"); sp. release (); // the following code is sometimes inaccurate because it is not integrated with the above Code into the atomic unit System. out. println ("Thread" + Thread. currentThread (). getName () + "Left, current" + (3-sp. availablePermits () + "concurrent") ;}}; service.exe cute (runnable );}}