Lock锁+CAS+与Synchronized比较

本文对比了Java中的Lock接口与Synchronized关键字,分析了Lock的灵活性和可扩展性,以及如何通过实现Lock接口创建自定义锁。文章还深入探讨了公平锁和非公平锁的概念,并通过ReentrantLock的源码分析了其内部实现,特别是AbstractQueuedSynchronizer(AQS)的队列结构。此外,文章介绍了CAS(Compare and Swap)算法,讨论了ABA问题及其解决方案,并提到了volatile关键字的作用和局限性。
摘要由CSDN通过智能技术生成
在大学时代接触Synchronized后,做的实验就一直用它处理线程安全问题。但是我们都知道它都是块状的粒度,粗大粗大的毛孔,喷着厚重的气息,方法执行到同步块,性能抖三抖,加在方法上,就锁住了整个实例对象,静态方法上,还锁住了整个类,所有这个类的实例对象都不能避免。monitorenter和monitorexit监视器实现的同步,虎视眈眈地看着每一个蹑手蹑脚进来的线程。步步紧跟,直到执行完同步块释放锁。
Lock()是一个接口,是Java中的更加轻量级,更加灵活的,甚至可以自定义的锁,通过实现这个接口,重写它里面的 lock() ,lockInterruptibly() , tryLock() , tryLock(long time, TimeUnit unit) , unlock() , newCondition() 这几个方法,可以实现自定义锁。
源码注释解析:
* {
   @code Lock} implementations provide more extensive locking
 * operations than can be obtained using {
   @code synchronized} methods
 * and statements.  They allow more flexible structuring, may have
 * quite different properties, and may support multiple associated
 * {
   @link Condition} objects.
 * A lock is a tool for controlling access to a shared resource by
 * multiple threads. Commonly, a lock provides exclusive access to a
 * shared resource: only one thread at a time can acquire the lock and
 * all access to the shared resource requires that the lock be
 * acquired first. However, some locks may allow concurrent access to
 * a shared resource, such as the read lock of a {
   @link ReadWriteLock}.
 * The use of {
   @code synchronized} methods or statements provides
 * access to the implicit monitor lock associated with every object, but
 * forces all lock acquisition and release to occur in a block-structured way:
 * when multiple locks are acquired they must be released in the opposite
 * order, and all locks must be released in the same lexical scope in which
 * they were acquired.
 * While the scoping mechanism for {
   @code synchronized} methods
 * and statements makes it much easier to program with monitor locks,
 * and helps avoid many common programming errors involving locks,
 * there are occasions where you need to work with locks in a more
 * flexible way. For example, some algorithms for traversing
 * concurrently accessed data structures require the use of
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值