Semaphore sema = new Semaphore(1);
Create a Semaphore object and the default initialization, the only one license, when multiple threads at the same time trying to get the license, must change is only one thread can access permission, then other threads will wait outside, when the first thread to release license, then wait for the thread has the right to obtain the license or is it just the first to arrive and wait for the thread shall be entitled to Who can help me, I will appreciate it very much
From the Semaphore
javadoc:
The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. In particular, barging is permitted, that is, a thread invoking
acquire()
can be allocated a permit ahead of a thread that has been waiting - logically the new thread places itself at the head of the queue of waiting threads. When fairness is set true, the semaphore guarantees that threads invoking any of theacquire
methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO). Note that FIFO ordering necessarily applies to specific internal points of execution within these methods. So, it is possible for one thread to invokeacquire
before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimedtryAcquire
methods do not honor the fairness setting, but will take any permits that are available.
So, you may choose when initializing a Semaphore
between two different orderings:
new Semaphore(1, true)
, then when multiple threads are waiting, the first thread that called acquire()
will be the first to receive a permit. That is, permits will be given to threads in the order that the threads requested them.new Semaphore(1, false)
or equivalently new Semaphore(1)
, then whenever a thread calls acquire()
, it will become the first thread in line to get a permit. That is, when a permit becomes available, the last thread to call acquire()
will be the first thread to receive it.