简体   繁体   English

带锁的Java多线程同步

[英]Java Multihreading Synchronization with Lock

In Java we can implements fairness by using Lock interface and ReentrantLock class as follows : 在Java中,我们可以通过使用Lock接口和ReentrantLock类来实现公平性,如下所示:

Lock lock=new ReentrantLock(true);

Once we implement fairness then in the case of multiple threads waiting to access the lock, the one which is waiting for most duration is given access to lock. 一旦我们实现公平性,那么在多个线程等待访问锁的情况下,等待大多数持续时间的那个被授予对锁的访问权。

Can anybody provide details of how JVM keep the track of threads waiting for long time ie how fairness is implemented by JVM . 任何人都可以提供JVM如何跟踪线程等待很长时间的细节,即JVM如何实现公平性。

The details are in the source code. 详细信息在源代码中。 And the source code can be found by Googling for: Googling可以找到源代码:

  • "java.util.concurrent.locks.ReentrantLock source" “java.util.concurrent.locks.ReentrantLock source”
  • "java.util.concurrent.locks.AbstractQueuedSynchronizer source" “java.util.concurrent.locks.AbstractQueuedSynchronizer source”

The code is exceptionally well commented. 该代码得到了极好的评论。

The short answer is that each lock has a queue of waiting threads that is implemented as a linked list. 简短的回答是每个锁都有一个等待线程的队列,它被实现为一个链表。

  • In the "fair" case, a thread that tries to acquire the lock when the queue is non-empty is added to the end of the queue. 在“公平”情况下,在队列非空时尝试获取锁的线程被添加到队列的末尾。

  • In the "unfair" case, a thread may barge in if the lock is currently free. 在“不公平”的情况下,如果锁当前是空闲的,则线程可能会插入。 This gives better performance because you don't need to do a thread context switch which entails a syscall. 这样可以提供更好的性能,因为您不需要执行需要系统调用的线程上下文切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM