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 ().
Related methods: Acquire
Acquire () throws Interruptedexception
-
The
-
gets a license from this semaphore, blocking the thread until a license is provided, or the thread is interrupted. Gets a license (if one is provided) and returns immediately, minus 1 of the available licenses.
- some other threads call the
release ()
method of this semaphore, And the current thread is the next thread to be assigned a license, or
- some other thread interrupts the current thread.
If the current thread:
- is set to on by this method, or
-
interrupted
while waiting for permission.
interruptedexception is thrown, and the current thread's interrupted state is cleared.
-
-
-
-
-
Thrown:
-
InterruptedException
-If the current thread is interrupted
Release
Release ()
-
release a license to return it to the semaphore. Release a license and increase the number of licenses available by 1. If any thread attempts to obtain a license, select a thread and give it the license that was just released. The thread is then enabled (or re-enabled) for thread scheduling purposes.
A thread that does not require the release of a license must be called acquire()
to obtain a license. The correct usage of semaphores is established by programming conventions in the application.
-
-
Related examples:
The following example allows only 5 threads to enter the code between execution acquire () and release () at the same time:
Public classSemaphoretest { Public Static voidMain (string[] args) {//thread PoolExecutorservice exec =Executors.newcachedthreadpool (); //can only be accessed by 5 threads at a time FinalSemaphore semp =NewSemaphore (5); //simulate 20 Client access for(intindex = 0; Index < 20; index++) { Final intNO =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 (); } }
Java Multi-Threading Semaphore (semaphore)