优先获取信号量阻塞线程的方法?

Acquire method of Semaphore blocked thread with priority?

信号量 sema = new 信号量(1);

创建一个Semaphore对象并默认初始化,只有一个license,当多个线程同时试图获取license时,必须改成只有一个线程可以访问权限,然后其他线程会在外面等待,当第一个线程释放许可,然后等待线程有权获得许可或者它只是第一个到达并等待线程应有权 谁能帮助我,我将不胜感激

来自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 the acquire 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 invoke acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed tryAcquire methods do not honor the fairness setting, but will take any permits that are available.

因此,您可以在初始化 Semaphore 时选择两种不同的顺序:

  • 如果用new Semaphore(1, true)初始化,那么当多个线程等待时,第一个调用acquire()的线程将最先获得许可。也就是说,将按照线程请求它们的顺序向线程提供许可。
  • 如果改为使用 new Semaphore(1, false)equivalently new Semaphore(1) 进行初始化,那么每当线程调用 acquire() 时,它将成为第一个获得许可的线程.也就是说,当许可可用时,最后一个调用 acquire() 的线程将是第一个接收它的线程。