Java 7 multithreading – semaphore — reprint

Semaphore is used to save the number of currently available licenses. This is achieved by sharing locks. According to the acquisition principle of shared lock, semaphore is divided into "fair semaphore" and "unfair semaphore".

The mechanism of releasing semaphores of "fair semaphore" and "unfair semaphore" is the same! The difference is their semaphore acquisition mechanism: when a thread attempts to obtain semaphore permission, for a fair semaphore, if the current thread is not at the head of the queue, it will wait in the queue; For unfair semaphores, whether the current thread is at the head of the queue or not, it will directly obtain the semaphore. The difference is reflected in the different implementation of their tryacquireshared() function.

If you want to use a semaphore object, first get the object through the constructor, as follows:

Then you can call the semaphore object to obtain the semaphore, as follows:

1. Acquisition of fair semaphore

First, let's look at the acquisition of fair semaphore. The method is as follows:

If the tryacquireshared() method fails, it usually returns a quantity less than 0. Tryacquireshared() corresponding to fair lock in semaphore is implemented as follows:

The returned value is remaining. If it is - 1, it indicates that the acquisition failed. If it is > = 0, it indicates whether other share acquisition operations can succeed.

If the above method fails, call the doAcquireSharedInterruptibly () method as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>