Detailed explanation of semaphore counting semaphore in Java Concurrent Programming
Semaphore is a counting semaphore, and its essence is a shared lock. Semaphores maintain a semaphore permission set. Threads can obtain semaphore permission by calling acquire(); When there is a license available in the semaphore, the thread can obtain the license; Otherwise, the thread must wait until a license is available. A thread can release its semaphore license through release() (it must be released after running out of semaphores, otherwise other threads may not be able to obtain semaphores).
Simple example:
Execution results:
Thread 1 and thread 2 will execute concurrently because the sum of semaphores does not exceed the total semaphore. Thread 3 can continue to execute only after the semaphores are released by the current two threads.
Source code analysis:
1. Constructor
The semaphore value is initialized in the constructor, which is finally the value of the lock flag bit state
2、Semaphore. acquire(n); It is simply understood as obtaining lock resources. If thread blocking cannot be obtained
The operation in acquire shared interruptibly is to obtain lock resources. If it can be obtained, state = state permissions. Otherwise, the thread will be blocked
The operation in tryacquireshared is to try to obtain the semaphore value, which is simply state = state acquire. If it is less than 0, a negative value will be returned; otherwise, it will be greater than the new value, and then judge whether the thread will be blocked
The operation in doacquireeshared interrupt is simply to add the current thread to the FIFO queue and block the current thread.
3、Semaphore. Release (int permissions). The implementation of this function is to set state = state + permissions and arouse the blocked threads in the FIFO queue.
The operation in releaseshared is to set state = state + permissions and wake up the blocked thread in the FIFO queue.
Tryrereleaseshared sets state to state = state + arg
Doreleaseshared() invokes blocked threads in FIFO queues
Summary: semaphore simply sets a semaphore pool state. When the thread executes, it will get the value from the state. If it can be obtained, the thread executes, and returns the obtained resources to the semaphore pool after execution, and evokes other blocked threads; If the resources in the semaphore pool cannot meet the needs of a thread, the thread is blocked.
Semaphore source code:
summary
The above is all about the detailed explanation of semaphore counting semaphore in Java Concurrent Programming in this paper. I hope it will be helpful to you. Interested friends can continue to refer to this site: re entry lock and read-write lock of Java Concurrent Programming, detailed solution of high concurrency of Java system, three implementation example codes of Java high concurrency lock, etc. if there are any problems, you can leave a message for exchange and discussion. Thank you for your support!