gpt4 book ai didi

java - Java AQS如何支持不公平锁定?

转载 作者:行者123 更新时间:2023-12-03 13:02:04 25 4
gpt4 key购买 nike

在AQS的文档中,第一行说

Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues.


由于AQS是基于FIFO等待队列的,因此我认为自然是公平的。但是在实现 SamephoreReentrantLock等许多地方,AQS既有公平版本,也有不公平版本。
所以我想知道AQS如何支持不公平锁定。
另外,我在文档中找到了这些行。但是我不明白。线程如何比已经在队列中的其他线程优先插入?

Even though this class is based on an internal FIFO queue, it does not automatically enforce >FIFO acquisition policies. The core of exclusive synchronization takes the form:

Acquire:while (!tryAcquire(arg)) {enqueue thread if it is not already queued;possibly block current thread;}

Release:if (tryRelease(arg))unblock the first queued thread;

(Shared mode is similar but may involve cascading signals.)Because checks in acquire are invoked before enqueuing, a newly acquiring thread may bargeahead of others that are blocked and queued.

最佳答案

How does a thread barge ahead of others which are already in the queue?在不公平模式下,新线程将尝试首先获取锁定。如果失败,则将其插入队列。
例子:

  • Thread1持有锁;
  • Thread2在队列中等待;
  • Thread1释放锁定;
  • 几乎同时,Thread3尝试获取锁。在不公平模式下运行时,允许Thread3在通知Thread2之前获取锁。但是在公平模式下,将不允许使用Thread3。
  • Thread3释放锁定;
  • Thread2获得了锁;
  • 关于java - Java AQS如何支持不公平锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64659499/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com