深入浅出java并发编程(ReentrantLock)-创新互联
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {lock.lock();
try {//
} finally {lock.unlock();
}
}
来自源码注释中的官方示例。
成都创新互联主要企业基础官网建设,电商平台建设,移动手机平台,微信平台小程序开发等一系列专为中小企业定制网站建设产品体系;应对中小企业在互联网运营的各种问题,为中小企业在互联网的运营中保驾护航。源码package java.util.concurrent.locks;
public class ReentrantLock implements Lock, java.io.Serializable {}
Lock接口void lock();
void lockInterruptibly() throws InterruptedException;
Condition newCondition();
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
加锁:lock、lockInterruptibly、tryLock、tryLock。
解锁:unlock
拿到Condition:Condition
有两个方法可以响应中断信号(带有 throws InterruptedException的方法)lockInterruptibly 和 tryLock。
public void lock() {sync.lock();
}
public void lockInterruptibly() throws InterruptedException {sync.acquireInterruptibly(1);
}
public Condition newCondition() {return sync.newCondition();
}
public boolean tryLock() {return sync.nonfairTryAcquire(1);
}
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
public void unlock() {sync.release(1);
}
从这里可以看到,所有锁的实现都是基于AQS这个类,这里不做过多赘述。
public 方法 构造函数public ReentrantLock() {sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {sync = fair ? new FairSync() : new NonfairSync();
}
fair – true if this lock should use a fair ordering policy ,公平锁也就是排队锁。
构造函数在这个最重要的用处就是给sync赋值。
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer {}
getHoldCountpublic int getHoldCount() {return sync.getHoldCount();
}
the number of holds on this lock by the current thread, or zero if this lock is not held by the current thread
当前线程持有锁的次数,如果当前线程没有持有锁则返回0。
getQueueLengthpublic final int getQueueLength() {return sync.getQueueLength();
}
the estimated number of threads waiting for this lock.
返回有多少线程在等待锁。
getWaitQueueLengthpublic int getWaitQueueLength(Condition condition) {if (condition == null) {throw new NullPointerException();
}
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) {throw new IllegalArgumentException("not owner");
}
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject) condition);
}
返回在指定Condition上等待的线程数量。
hasQueuedThreadpublic final boolean hasQueuedThread(Thread thread) {return sync.isQueued(thread);
}
true if the given thread is queued waiting for this lock ,如果给定的线程在队列等锁则返回true。
hasQueuedThreadspublic final boolean hasQueuedThreads() {return sync.hasQueuedThreads();
}
public final boolean hasQueuedThreads() {return head != tail;
}
true if there maybe other threads waiting to acquire the lock,如果可能有其他线程正在等待获取锁,返回true。
底层判断队列的头和尾是否相等,如果不相等代表有其他线程在排队。
hasWaiterspublic final boolean hasWaiters(ConditionObject condition) {if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.hasWaiters();
}
true if there are any waiting threads,如果有任何等待线程,则为true
isFairpublic final boolean isFair() {return sync instanceof FairSync;
}
判断是否是公平锁
isHeldByCurrentThreadpublic boolean isHeldByCurrentThread() {return sync.isHeldExclusively();
}
true if current thread holds this lock and false otherwise,如果当前线程持有该锁,则为true,否则为false
isLockedpublic boolean isLocked() {return sync.isLocked();
}
true if any thread holds this lock and false otherwise,如果任何线程持有此锁,则为true,否则为false
synchronized 对比- 一个是内置关键字,一个是并发包工具类。
- sync不响应中断,ReentrantLock部分方法响应中断。
- sync会一直阻塞,ReentrantLock带有time参数的可以提前放弃。
- 加锁语法,ReentrantLock需要搭配异常捕获机制保证锁一定会被释放。
lock.lock();
//1
try {//2
} finally {lock.unlock();
}
try { //3
lock.lock();
//4
} finally {lock.unlock();
}
我的思考:
- 方式1在1处如果有其他错误的代码会导致加锁后未释放,死锁。
- 方式2在3处如果有其他错误的代码会导致不进行解锁,死锁。
- 如果使用方式1,lock需要紧贴try代码块。
- 如果使用方式2,try后紧跟try代码块。
- 官方推荐方式1。
ReentrantLock 对比 sync 有以下几个特点 ,ReentrantLock 的解锁需要放到 finally 中,避免程序异常导致锁无法释放。
三个重要的内部类 Syncabstract static class Sync extends AbstractQueuedSynchronizer {}
Uses AQS state to represent the number of holds on the lock. 使用AQS状态来表示持有锁的次数。
FairSyncstatic final class FairSync extends Sync {final void lock() {acquire(1);
}
protected final boolean tryAcquire(int acquires) {final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {int nextc = c + acquires;
if (nextc< 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
NonfairSyncstatic final class NonfairSync extends Sync {
final void lock() {if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);
}
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
网站标题:深入浅出java并发编程(ReentrantLock)-创新互联
当前链接:http://pwwzsj.com/article/ehdhh.html