不公平
是指当准备好通过新线程获取锁时,该锁不能保证谁获得了该锁的公平性(假设当时有多个线程在请求该锁)。换句话说,可以想象一个线程可能会连续饿死,因为其他线程总是设法任意获得锁而不是锁。
公平 模式的行为更像是先到先服务,在这种情况下,线程被保证达到一定程度的公平性,即它们将以公平的方式获得锁(例如,在线程开始等待很长时间之后)。
编辑
这是一个演示锁公平性的示例程序(以先到先得的方式请求对公平锁的写锁请求)。比较
FAIR = true( 总是 按顺序提供
FAIR =false线程)与( 有时 不按顺序提供线程)的结果。
import java.util.concurrent.locks.ReentrantReadWriteLock;public class FairLocking { public static final boolean FAIR = true; private static final int NUM_THREADS = 3; private static volatile int expectedIndex = 0; public static void main(String[] args) throws InterruptedException { ReentrantReadWriteLock.WriteLock lock = new ReentrantReadWriteLock(FAIR).writeLock(); // we grab the lock to start to make sure the threads don't start until we're ready lock.lock(); for (int i = 0; i < NUM_THREADS; i++) { new Thread(new ExampleRunnable(i, lock)).start(); // a cheap way to make sure that runnable 0 requests the first lock // before runnable 1 Thread.sleep(10); } // let the threads go lock.unlock(); } private static class ExampleRunnable implements Runnable { private final int index; private final ReentrantReadWriteLock.WriteLock writeLock; public ExampleRunnable(int index, ReentrantReadWriteLock.WriteLock writeLock) { this.index = index; this.writeLock = writeLock; } public void run() { while(true) { writeLock.lock(); try { // this sleep is a cheap way to make sure the previous thread loops // around before another thread grabs the lock, does its work, // loops around and requests the lock again ahead of it. Thread.sleep(10); } catch (InterruptedException e) { //ignored } if (index != expectedIndex) { System.out.printf("Unexpected thread obtained lock! " + "Expected: %d Actual: %d%n", expectedIndex, index); System.exit(0); } expectedIndex = (expectedIndex+1) % NUM_THREADS; writeLock.unlock(); } } }}再次编辑
关于您的更新,使用非公平锁定,并不是说线程获得锁的可能性很小,而是线程要稍等一会儿的可能性很小。
现在,通常随着饥饿期的增加,实际发生的时间长度的可能性会降低……就像连续10次翻转硬币“头”比连续9次翻转硬币“头”的可能性较小。
但是,如果用于多个等待线程的选择算法是非随机的,例如“具有字母名字的线程始终获得锁定”,那么您可能会遇到真正的问题,因为随着线程数量的增加,概率并不一定会降低更饿了…如果将一枚硬币称重为“正面”,则连续10个正面的可能性实际上与9个连续正面的可能性差不多。
我相信在非公平锁定的实现中,会使用某种“公平”的硬币。因此,问题实际上变成了公平性(以及 延迟
)与吞吐量之间的关系。使用非公平锁定通常可以提高吞吐量,但要以偶尔出现的锁定请求延迟时间为代价。哪种更适合您取决于您自己的要求。



