ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.Semaphore; Public classSemaphoreTest1 {Private Static Final intSem_max = 10; Public Static voidMain (string[] args) {Semaphore sem=NewSemaphore (Sem_max); //Create a thread poolExecutorservice ThreadPool = Executors.newfixedthreadpool (3); //perform tasks in a thread poolThreadpool.execute (NewMyThread (SEM, 5)); Threadpool.execute (NewMyThread (SEM, 4)); Threadpool.execute (NewMyThread (SEM, 7)); //Close PoolThreadpool.shutdown (); }}classMyThreadextendsThread {Private volatileSemaphore sem;//Signal Volume Private intCount//the size of the request SemaphoreMyThread (Semaphore sem,intcount) { This. SEM =sem; This. Count =count; } Public voidrun () {Try { //get count licenses from semaphoresSem.acquire (count); Thread.Sleep (2000); System.out.println (Thread.CurrentThread (). GetName ()+ "Acquire count=" +count); } Catch(interruptedexception e) {e.printstacktrace (); } finally { //releases a given number of licenses and returns them to the semaphore. Sem.release (count); System.out.println (Thread.CurrentThread (). GetName ()+ "Release" + Count + ""); } }}
Pool-1-thread-1 acquire count=5Pool-1-thread-2 acquire count=4pool-1-thread-1 Release 5Pool -1-thread-2 Release 4pool-1-thread-3 acquire count=7Pool-1-thread-3 release 7 The results show that the total number of licenses for the SEM is 10, a total of 3 threads, the number of semaphores to be obtained is 5,4, 7 respectively. After the first two threads have obtained a license to the semaphore, the remaining number of licenses available in the SEM is 1; therefore, the last thread must wait for the first two threads to release the semaphore licenses they hold before acquiring 7 semaphore licenses.
Semaphore is a count semaphore, and its essence is a "shared lock". The semaphore maintains a semaphore license set. A thread can obtain a semaphore's license by calling acquire (), and the thread can obtain the license when there is a license available in the semaphore, otherwise the thread must wait until a license is available. The thread can release () The semaphore license it holds.
Java----Multi-threaded semaphore signal Volume