ReadWriteLock
读锁:允许多个线程对数据进行读取操作,写锁:对数据进行写操作的时候,必须独占资源
代码实现
package com.wanmait.demo; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Resource <E> { private ReadWriteLock lock = new ReentrantReadWriteLock(); private E data; public void set(E e) { this.lock.writeLock().lock(); //获得写锁 //其他线程不能使用资源 this.data = e; this.lock.writeLock().unlock(); //释放写锁 } public E get() { this.lock.readLock().lock(); //获得读锁 try { return this.data; } finally { this.lock.readLock().unlock(); //释放写锁 } } }
StampedLock
三种模式,读锁,写锁,乐观读锁。
代码实现:
package com.wanmait.demo; import java.util.concurrent.locks.StampedLock; public class Resource<E> { private StampedLock lock = new StampedLock(); private E data; public void set(E e) { long id = this.lock.writeLock(); //获得写锁 this.data = e; this.lock.unlockWrite(id); //释放写锁 } public E get() { long id = this.lock.tryOptimisticRead(); //尝试乐观读 if(this.lock.validate(id))//验证乐观锁是否成功 { return this.data; } else//乐观锁失败 { id = this.lock.readLock(); //获得读锁 try { return this.data; } finally { this.lock.unlockRead(id); //释放读锁 } } } }
tryOptimisticRead()方法 是尝试乐观读方法,如果乐观读没有成功,就获得读锁,重新读取
0条评论
点击登录参与评论